<template>
  <div style="overflow-y: scroll;" :style=divStyle :loading="dataLoading">
    <el-card shadow="always">
      <el-button type="primary" plain size="large" @click="close()">返回</el-button>
      <span style="margin-left: 20px;">{{ isView ? '查看食谱' : form.recipeId ? '编辑食谱' : '食谱管理' }}</span>
      <el-divider />
      <div style="font-size: 14px; margin-top: -10px;margin-bottom: -10px;">基本信息</div>
      <el-divider />
      <div width="1024px">
        <el-form ref="foodIngredientFormRef" :model="form" :rules="rules" append-to-body label-width="130px">
          <el-row style="margin-top: 20px;">
            <el-col :span="24" style="margin-left: 100px;">
              <div><span style="color: red;">&nbsp; </span></div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="2" style="margin-left: -100px;">
            </el-col>
            <el-col :span="9">
              <el-form-item label="基本膳食" prop="baseDiet">
                <el-radio-group v-model="form.baseDiet" :disabled="isView">
                  <el-radio v-for="item in dietary_types" :key="item.value" :label="item.value">{{ item.label
                  }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="2">
            </el-col>
            <el-col :span="9">
            </el-col>
            <el-col :span="2">
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="2" style="margin-left: -100px;">
            </el-col>
            <el-col :span="9">
              <el-form-item label="餐次" prop="mealTime">
                <el-checkbox-group v-model="form.mealTimes" :disabled="isView">
                  <el-checkbox v-for="item in meal_times" :key="item.value" :label="item.label" :value="item.value" />
                </el-checkbox-group>

              </el-form-item>
            </el-col>
            <el-col :span="2">
            </el-col>
            <el-col :span="9">
            </el-col>
            <el-col :span="2">
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="2" style="margin-left: -100px;">
            </el-col>
            <el-col :span="9">
              <el-form-item label="食谱名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" :disabled="isView" />
              </el-form-item>
            </el-col>
            <el-col :span="2">
            </el-col>
            <el-col :span="9">
              <el-form-item label="食谱分类" prop="categoryId">
                <el-select v-model="form.categoryId" placeholder="请选择" clearable :disabled="isView">
                  <el-option v-for="dict in recipeCategoryList" :key="dict.recipeCategoryId" :label="dict.name"
                    :value="dict.recipeCategoryId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="2" style="margin-left: -100px;">
            </el-col>
            <el-col :span="9">
              <el-form-item label="食谱价格" prop="price">
                <el-input v-model="form.price" placeholder="请输入" :disabled="isView" />
              </el-form-item>
            </el-col>
            <el-col :span="2">
            </el-col>
            <el-col :span="9">
              <el-form-item label="适用疾病" prop="suitableDisease">
                <span style="width: 100%;" @click="openAvoidDiseaseDialog">
                  <el-input v-model="form.suitableDisease" placeholder="请选择" :disabled="isView" readonly>
                    <template #suffix>
                      <el-icon class="el-input__icon">
                        <ArrowDown />
                      </el-icon>
                    </template>
                  </el-input>
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="2">
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="2" style="margin-left: -100px;">
            </el-col>
            <el-col :span="9">
              <el-form-item label="忌食病症" prop="avoidDisease">
                <span style="width: 100%;" @click="openAvoidDiseaseDialog2">
                  <el-input v-model="form.avoidDisease" placeholder="请选择" :disabled="isView" readonly>
                    <template #suffix>
                      <el-icon class="el-input__icon">
                        <ArrowDown />
                      </el-icon>
                    </template>
                  </el-input></span>
              </el-form-item>
            </el-col>
            <el-col :span="2">
            </el-col>
            <el-col :span="9">
              <el-form-item label="适用科室" prop="suitableDept">
                <el-tree-select :disabled="isView" v-model="form.suitableDeptList" show-checkbox multiple
                  :default-expanded-keys="[2, 3]" :data="enabledDeptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' } as any" value-key="id"
                  placeholder="请选择" />

              </el-form-item>
            </el-col>
            <el-col :span="2">
            </el-col>

          </el-row>

          <el-row>
            <el-col :span="2" style="margin-left: -100px;">
            </el-col>
            <el-col :span="9">
              <el-form-item label="智能推荐" prop="smartRecommend">
                <el-radio-group v-model="form.smartRecommend" :disabled="isView">
                  <el-radio v-for="item in intelligent_recommendation" :key="item.value" :label="item.value">{{
                    item.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="2">
            </el-col>
            <el-col :span="2">
            </el-col>
          </el-row>
        </el-form>

        <el-divider />
        <div style="font-size: 14px;margin-top: -10px;margin-bottom: -10px;">食材组成</div>
        <el-divider />
        <div style="margin-top: 10px; margin-bottom: 20px;"><span>食材总量：{{ quantitySum }} g</span><span
            style="margin-left: 100px;">膳食总热量：{{ caloriesSum }}kcal</span></div>


        <el-table border :data="selectedIngredientListBak">
          <el-table-column label="食材名称" align="center" prop="name" />
          <el-table-column label="食材分类" align="center" prop="subCategory" />
          <el-table-column label="用量" align="center" prop="quantity">
            <template #default="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入" :disabled="isView"
                @input="editFoodquantity(scope.row)">
                <template #append><span>{{ scope.row.unitName }}</span></template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="热量（kcal）" align="center" prop="caloriesForInput" />
          <el-table-column label="备注" align="center" prop="remark">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" :disabled="isView" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="!isView">
            <template #default="scope">
              <el-tooltip content="删除" placement="top">
                <el-button link type="danger" icon="Delete" @click="deleteFoodquantity(scope.row)">删除</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-row :gutter="10" class="mb8">
          <el-col :span="8">
          </el-col>
          <el-col :span="8" align="center">
            <el-link type="primary" icon="Plus" @click="openAddFoodDialog()"
              style="margin-top: 20PX;margin-bottom: 10px;" v-if="!isView">添加食材</el-link>
          </el-col>
          <el-col :span="8">
          </el-col>
        </el-row>

        <el-row :gutter="10" class="mb8">
          <el-col :span="24">
            <el-form-item label="制作方式" prop="cookingMethod">
              <el-input v-model="form.cookingMethod" type="textarea" placeholder="请输入" :disabled="isView" :rows="3"
                maxlength="3000" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>


  <el-card shadow="always" class="card-footer">
    <div>
      <el-button type="primary" size="large" plain @click="showNutrientAnalysisDialog">
        &nbsp;&nbsp;&nbsp;营养数据分析&nbsp;&nbsp;&nbsp;
      </el-button>
      <el-button type="primary" size="large" @click="submitForm" v-if="!isView">
        &nbsp;&nbsp;&nbsp;提交&nbsp;&nbsp;&nbsp;
      </el-button>
    </div>
  </el-card>

  <!-- 适用疾病对话框 -->
  <el-dialog :title="dialog.title" v-model="dialog.visible" width="78%" append-to-body style="height: 750px;">
    <el-row :gutter="10" class="mb8">
      <el-col :span="24">
        <!-- <span class="diagnosis-tag" :class="{'diagnosisActive':diseaseLabelQuery.category==1}">常见营养诊断</span>
        <span class="diagnosis-tag" :class="{'diagnosisActive':diseaseLabelQuery.category==2}">ICD诊断</span>
        <span class="diagnosis-tag" :class="{'diagnosisActive':diseaseLabelQuery.category==3}">营养诊断</span> -->
        <span class="diagnosis-tag" :class="{ 'diagnosisActive': diseaseLabelQuery.category == item.value }"
          v-for="item in disease_label" :key="item.value" @click="changeTag(item.value)">{{ item.label }}</span>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="12">
        <el-form-item prop="labelCode">
          <el-input v-model="diseaseLabelQuery.labelCode" placeholder="疾病名称/疾病编码" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" align="left">
        <el-button type="primary" @click="getDiseaseLabelList">查询</el-button>
        <el-button type="primary" @click="addDiseaseLabelDialog">新增疾病标签</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="12">
        <div style="height: 400px;overflow-y: scroll;">
          <el-table border stripe :data="diseaseLabelList" @select-all="handleSelectAllChange"
            @select="handleSelectChange" ref="diseaseLabelRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="疾病/部位名称" align="center" prop="labelName" />
            <el-table-column label="疾病/部位编码" align="center" prop="labelCode" />
            <el-table-column label="所属分类" align="center" prop="categoryName" />
          </el-table>
        </div>
        <div style="margin-left: 10px;width: 100%;">
          <pagination v-show="total > -1" :total="total" v-model:page="diseaseLabelQuery.pageNum"
            layout="total, sizes, prev, pager, next" v-model:limit="diseaseLabelQuery.pageSize"
            @pagination="getDiseaseLabelList" size="small" />
        </div>
      </el-col>
      <el-col :span="12" align="right">
        <div style="height: 400px;overflow-y: scroll;">
          <el-table border :data="selecteddiseaseLabelList">
            <el-table-column label="疾病/部位名称" align="center" prop="labelName" />
            <el-table-column label="疾病/部位编码" align="center" prop="labelCode" />
            <el-table-column label="所属分类" align="center" prop="categoryName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button link type="danger" icon="Delete" @click="handleSelectedDelete(scope.row)">删除</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-left: 10px;margin-top:36px;width: 100%;text-align: left;">
          <span style="color: rgb(118, 180, 244);">已选：{{ selecteddiseaseLabelList.length }}项</span>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="24" align="center">
        <el-button type="primary" @click="handleSelectedconfirm">&nbsp;&nbsp;&nbsp;确定&nbsp;&nbsp;&nbsp;</el-button>
        <el-button @click="dialog.visible = !dialog.visible">&nbsp;&nbsp;&nbsp;取消&nbsp;&nbsp;&nbsp;</el-button>
      </el-col>
    </el-row>
  </el-dialog>

  <!-- 适用疾病：添加或修改疾病/部位标签对话框 -->
  <el-dialog :title="diseaseLabelDialog.title" v-model="diseaseLabelDialog.visible" width="700px" append-to-body>
    <el-form ref="diseaseLabelFormRef" :model="diseaseLabelFormData" :rules="diseaseLabelRules" label-width="150px">
      <el-form-item label="疾病/部位名称" prop="labelName">
        <el-input v-model="diseaseLabelFormData.labelName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="所属分类" prop="category">
        <el-select v-model="diseaseLabelFormData.category" placeholder="请选择" clearable>
          <el-option v-for="dict in disease_label" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="疾病/部位编码" prop="labelCode">
        <el-input v-model="diseaseLabelFormData.labelCode" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="diseaseLabelSubmitForm">确 定</el-button>
        <el-button @click="diseaseLabelCancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>


  <!-- 忌食病症对话框 -->
  <el-dialog :title="dialog2.title" v-model="dialog2.visible" width="78%" append-to-body>
    <el-row :gutter="10" class="mb8">
      <el-col :span="24">
        <!-- <span class="diagnosis-tag" :class="{'diagnosisActive':diseaseLabelQuery.category==1}">常见营养诊断</span>
        <span class="diagnosis-tag" :class="{'diagnosisActive':diseaseLabelQuery.category==2}">ICD诊断</span>
        <span class="diagnosis-tag" :class="{'diagnosisActive':diseaseLabelQuery.category==3}">营养诊断</span> -->
        <span class="diagnosis-tag" :class="{ 'diagnosisActive': diseaseLabelQuery.category == item.value }"
          v-for="item in disease_label" :key="item.value" @click="changeTag(item.value)">{{ item.label }}</span>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="12">
        <el-form-item prop="labelCode">
          <el-input v-model="diseaseLabelQuery.labelCode" placeholder="疾病名称/疾病编码" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" align="left">
        <el-button type="primary" @click="getDiseaseLabelList">查询</el-button>
        <el-button type="primary" @click="addDiseaseLabelDialog2">新增疾病标签</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="12">
        <div style="height: 400px;overflow-y: scroll;">
          <el-table border stripe :data="diseaseLabelList" @selection-change="handleSelectionChange2"
            ref="diseaseLabelRef2" @select-all="handleSelectAllChange2" @select="handleSelectChange2">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="疾病/部位名称" align="center" prop="labelName" />
            <el-table-column label="疾病/部位编码" align="center" prop="labelCode" />
            <el-table-column label="所属分类" align="center" prop="categoryName" />
        </el-table>
        </div>
        <div style="margin-left: 10px;width: 100%;">
          <pagination v-show="total > -1" :total="total" v-model:page="diseaseLabelQuery.pageNum"
            layout="total, sizes, prev, pager, next" v-model:limit="diseaseLabelQuery.pageSize"
            @pagination="getDiseaseLabelList" size="small" />
        </div>
      </el-col>
      <el-col :span="12" align="right">
        <div style="height: 400px;overflow-y: scroll;">
          <el-table border :data="selecteddiseaseLabelList2">
            <el-table-column label="疾病/部位名称" align="center" prop="labelName" />
            <el-table-column label="疾病/部位编码" align="center" prop="labelCode" />
            <el-table-column label="所属分类" align="center" prop="categoryName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template #default="scope">
              <el-tooltip content="删除" placement="top">
                  <el-button link type="danger" icon="Delete" @click="handleSelectedDelete2(scope.row)">删除</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        </div>
        <div style="margin-left: 10px;margin-top:36px;width: 100%;text-align: left;">
          <span style="color: rgb(118, 180, 244);">已选：{{ selecteddiseaseLabelList2.length }}项</span>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="24" align="center">
        <el-button type="primary" @click="handleSelectedconfirm2">&nbsp;&nbsp;&nbsp;确定&nbsp;&nbsp;&nbsp;</el-button>
        <el-button @click="dialog2.visible = !dialog2.visible">&nbsp;&nbsp;&nbsp;取消&nbsp;&nbsp;&nbsp;</el-button>
      </el-col>
    </el-row>
  </el-dialog>


  <!-- 忌食病症：添加或修改疾病/部位标签对话框 -->
  <el-dialog :title="diseaseLabelDialog2.title" v-model="diseaseLabelDialog2.visible" width="700px" append-to-body>
    <el-form ref="diseaseLabelFormRef2" :model="diseaseLabelFormData2" :rules="diseaseLabelRules2" label-width="150px">
      <el-form-item label="疾病/部位名称" prop="labelName">
        <el-input v-model="diseaseLabelFormData2.labelName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="所属分类" prop="category">
        <el-select v-model="diseaseLabelFormData2.category" placeholder="请选择" clearable>
          <el-option v-for="dict in disease_label" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="疾病/部位编码" prop="labelCode">
        <el-input v-model="diseaseLabelFormData2.labelCode" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="diseaseLabelSubmitForm2">确 定</el-button>
        <el-button @click="diseaseLabelCancel2">取 消</el-button>
      </div>
    </template>
  </el-dialog>


  <!--添加食材话框 -->
  <el-dialog :title="dialog3.title" v-model="dialog3.visible" width="55%" append-to-body>
    <el-row :gutter="10" class="mb8">
      <el-col :span="22">
        <el-form-item prop="name">
          <el-input v-model="foodIngredientQuery.name" placeholder="请输入食材名称" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="2" align="right">
        <el-button type="primary" @click="getListFoodIngredient">查询</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="10">
        <div style="height: 400px;overflow-y: scroll;">
          <el-tree style="max-width: 600px" :data="foodCategoryList"
            :props="{ value: 'foodCategoryId', label: 'name', children: 'children' } as any"
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="14" align="right">
        <div style="height: 330px;overflow-y: scroll;">
          <el-table border stripe :data="foodIngredientList" ref="foodIngredienRef" @select-all="handleSelectAllChange3"
            @select="handleSelectChange3">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="食材名称" align="center" prop="name" />
            <el-table-column label="可食部分（%）" align="center" prop="edibleRatio" />
          </el-table>
        </div>
        <div style="margin-left: 10px;width: 100%;">
          <pagination v-show="totalFood > -1" :total="totalFood" v-model:page="foodIngredientQuery.pageNum"
            layout="total, sizes, prev, pager, next" v-model:limit="foodIngredientQuery.pageSize"
            @pagination="getListFoodIngredient" size="small" />
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="24" align="center">
        <el-divider style="margin-bottom: -25px;" />
        <div style="margin-left: 10px;margin-top:36px;width: 100%;text-align: left;">
          <span>已选(<label style="color: rgb(118, 180, 244);">{{ selectedIngredientList.length }}</label>)：</span>
          <span>
            <el-tag v-for="tag in selectedIngredientList" :key="tag.foodIngredientId" closable
              style="margin-left: 5px;">
              {{ tag.name }}
            </el-tag>
          </span>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="24" align="center">
        <el-divider />
        <el-button type="primary" @click="handleSelectedconfirm3">&nbsp;&nbsp;&nbsp;确定&nbsp;&nbsp;&nbsp;</el-button>
        <el-button @click="dialog3.visible = !dialog3.visible">&nbsp;&nbsp;&nbsp;取消&nbsp;&nbsp;&nbsp;</el-button>
      </el-col>
    </el-row>
  </el-dialog>



  <!-- 营养数据分析 -->
  <el-dialog :title="dialog4.title" v-model="dialog4.visible" width="70%" append-to-body>
    <div class="p-2">
      <el-menu class="el-menu-demo" mode="horizontal" @select="handleMenumSelect" :default-active="currentIndex">
        <el-menu-item index="1">三大营养素分析</el-menu-item>
        <el-menu-item index="2">营养数据分析</el-menu-item>
      </el-menu>
    </div>

    <el-row :gutter="10" class="mb8" v-show="leftIndex == currentIndex">
      <el-col :span="14">
        <div style="margin-top: 20px;margin-bottom: 20px;">实际热量：{{ leftCalories }}kcal/d</div>
        <div style="height: 300px;">
          <el-table border stripe :data="leftList">
            <el-table-column label="三大营养素" align="center" prop="nutrientName" />
            <el-table-column label="质量（g）" align="center" prop="nutrientQuantity" >
              <template #default="scope">
                {{ scope.row.nutrientQuantity.toFixed(4)}}
              </template>
            </el-table-column>
            <el-table-column label="热量占比" align="center" prop="nutrientRatio" />
            <el-table-column label="参考值" align="center" prop="nutrientRefVal" />
          </el-table>
        </div>
      </el-col>
      <el-col :span="10" align="center">
        <div style="height: 300px;">
          <v-chart :option="pieOption" style="width: 400px; height: 200px;" class="chart-center" />
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8" v-show="rightIndex == currentIndex">
      <el-col :span="24">
        <div style="height: 400px;overflow-y: scroll;">
          <el-table border stripe :data="rightList">
            <el-table-column label="元素名称" align="center" prop="nutrientName" />
            <el-table-column label="单位" align="center" prop="nutrientUnit" />
            <el-table-column label="食谱营养素含量" align="center" prop="nutrientQuantity" />
          </el-table>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="24" align="center">
        <el-button type="primary"
          @click="dialog4.visible = !dialog4.visible">&nbsp;&nbsp;&nbsp;确定&nbsp;&nbsp;&nbsp;</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script setup name="FoodIngredient" lang="ts">
import { listTree } from '@/api/system/foodCategory';
import { FoodCategoryVO } from '@/api/system/foodCategory/types';
import { listDiseaseLabel, getDiseaseLabel, delDiseaseLabel, addDiseaseLabel, updateDiseaseLabel } from '@/api/system/diseaseLabel';
import { DiseaseLabelVO, DiseaseLabelQuery, DiseaseLabelForm } from '@/api/system/diseaseLabel/types';
import { listRecipe, getRecipe, delRecipe, addRecipe, updateRecipe, nutrientAnalysis } from '@/api/system/recipe';
import { RecipeVO, RecipeQuery, RecipeForm } from '@/api/system/recipe/types';
import { listRecipeCategory, getRecipeCategory, delRecipeCategory, addRecipeCategory, updateRecipeCategory } from '@/api/system/recipeCategory';
import { RecipeCategoryVO, RecipeCategoryQuery, RecipeCategoryForm } from '@/api/system/recipeCategory/types';
import { DeptTreeVO } from '@/api/system/dept/types';
import api from '@/api/system/user';
import { FoodIngredientVO, FoodIngredientQuery } from '@/api/system/foodIngredient/types';
import { listFoodIngredient, getFoodIngredient, delFoodIngredient, addFoodIngredient, updateFoodIngredient } from '@/api/system/foodIngredient';



const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { intelligent_recommendation, meal_times, dietary_types, disease_label, nutrient_reference } = toRefs<any>(
  proxy?.useDict('intelligent_recommendation', 'meal_times', 'dietary_types', 'disease_label', 'nutrient_reference'));

const foodCategoryList = ref<FoodCategoryVO[]>([]);
const diseaseLabelFormRef = ref<ElFormInstance>();
const diseaseLabelFormRef2 = ref<ElFormInstance>();
const foodIngredientFormRef = ref<ElFormInstance>();
const selecteddiseaseLabelList = ref<DiseaseLabelVO[]>([]);
const selecteddiseaseLabelList2 = ref<DiseaseLabelVO[]>([]);
const selecteddiseaseLabelListBak = ref<DiseaseLabelVO[]>([]);
const selecteddiseaseLabelListBak2 = ref<DiseaseLabelVO[]>([]);
const diseaseLabelList = ref<DiseaseLabelVO[]>([]);
const diseaseLabelList2 = ref<DiseaseLabelVO[]>([]);
const enabledDeptOptions = ref<DeptTreeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const dataLoading = ref(true);
const total = ref(0);
const totalFood = ref(0);
const recipeCategoryList = ref<RecipeCategoryVO[]>([]);
const diseaseLabelRef = ref<ElTableInstance>();
const diseaseLabelRef2 = ref<ElTableInstance>();
const foodIngredientList = ref<FoodIngredientVO[]>([]);
const selectedIngredientList = ref<FoodIngredientVO[]>([]);
const selectedIngredientListBak = ref<FoodIngredientVO[]>([]);
const foodIngredienRef = ref<ElTableInstance>();

const leftList = ref<FoodIngredientVO[]>([]);
const leftCalories = ref<number>(0.0);
const rightList = ref<FoodIngredientVO[]>([]);

const caloriesSum = ref('0.0000');
const quantitySum = ref('0.00');

const leftIndex = ref('1')
const rightIndex = ref('2')
const currentIndex = ref('1')


const pieOption = ref({
  legend: {
    orient: 'horizontal',
    bottom: 'bottom',
    data: ['蛋白质 30%', '脂肪 20%', '碳水化合物 50%']
  },
  title: {
    text: '三大营养素元素质量占比',
    left: 'center'
  },
  series: [
    {
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      labelLine: {
        show: false
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '30',
          fontWeight: 'bold'
        }
      },
      data: [
        { value: 30, name: '蛋白质 30%' },
        { value: 20, name: '脂肪 20%' },
        { value: 50, name: '碳水化合物 50%' },
      ]
    }
  ]
});

const divStyle = ref({
  height: '755px'
});

const isView = ref<boolean>(false)
const route = useRoute();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});


const diseaseLabelDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});


const diseaseLabelDialog2 = reactive<DialogOption>({
  visible: false,
  title: ''
});

const diseaseLabelQuery = ref<DiseaseLabelQuery>({
  labelCode: undefined,
  category: '1',
  pageNum: 1,
  pageSize: 10,
})

const foodIngredientQuery = ref<FoodIngredientQuery>({
  name: undefined,
  foodCategoryId: undefined,
  pageNum: 1,
  pageSize: 10,
})

const dialog2 = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialog3 = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialog4 = reactive<DialogOption>({
  visible: false,
  title: ''
});

const diseaseLabelFormData = ref<DiseaseLabelForm>({
  labelName: undefined,
  category: undefined,
  labelCode: undefined,
});

const diseaseLabelRules = ref({
  category: [
    { required: true, message: "所属分类不能为空", trigger: "blur" }
  ],
  labelName: [
    { required: true, message: "疾病/部位名称不能为22空", trigger: "blur" }
  ],
  labelCode: [
    { required: true, message: "疾病/部位编码不能为空", trigger: "blur" }
  ],
});

const diseaseLabelFormData2 = ref<DiseaseLabelForm>({
  labelName: undefined,
  category: undefined,
  labelCode: undefined,
});

const diseaseLabelRules2 = ref({
  category: [
    { required: true, message: "所属分类不能为空", trigger: "blur" }
  ],
  labelName: [
    { required: true, message: "疾病/部位名称不能为22空", trigger: "blur" }
  ],
  labelCode: [
    { required: true, message: "疾病/部位编码不能为空", trigger: "blur" }
  ],
});


const initFormData: RecipeForm = {
  recipeId: undefined,
  name: undefined,
  categoryId: undefined,
  baseDiet: '1',
  mealTime: undefined,
  price: '0.00',
  suitableDisease: undefined,
  avoidDisease: undefined,
  suitableDept: undefined,
  smartRecommend: '1',
  cookingMethod: undefined,
  status: undefined,
}
const data = reactive<PageData<RecipeForm, RecipeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    categoryId: undefined,
    baseDiet: undefined,
    mealTime: undefined,
    price: undefined,
    suitableDisease: undefined,
    avoidDisease: undefined,
    suitableDept: undefined,
    smartRecommend: undefined,
    cookingMethod: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    recipeId: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "食谱名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "食谱分类ID不能为空", trigger: "blur" }
    ],
    baseDiet: [
      { required: true, message: "基本膳食不能为空", trigger: "blur" }
    ],
    price: [
      { required: true, message: "食谱价格不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询食材分类列表 */
const getListTree = async () => {
  const res = await listTree();
  foodCategoryList.value = res.rows;

}

/** 关闭按钮 */
const close = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined,
    path: '/food/recipe'
  };
  proxy?.$tab.closeOpenPage(obj);
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DiseaseLabelVO[]) => {
  if (loading.value) {
    let tJson = ref({})
    selecteddiseaseLabelList.value.forEach(item => {
      tJson.value[item.labelId] = true;
    })

    diseaseLabelList.value.forEach(item => {
      if (tJson.value[item.labelId]) {
        diseaseLabelRef.value.toggleRowSelection(item, true);
      }
    })
    loading.value = false;
  }
}

/** 多选框选中数据 */
const handleSelectAllChange = (selection: DiseaseLabelVO[]) => {
  if (selection.length == 0) {
    selecteddiseaseLabelList.value = [];
  } else {
    let tJson = ref({})
    selecteddiseaseLabelList.value.forEach(item => {
      tJson.value[item.labelId] = true;
    })

    selection.forEach(item => {
      if (!tJson.value[item.labelId]) {
        selecteddiseaseLabelList.value.push(item);
      }
    })
  }
}

const handleSelectChange = (selection: DiseaseLabelVO[], row: DiseaseLabelVO) => {
  let addAction = ref<boolean>(false);
  if (selection.length > 0) {
    for (let item of selection) {
      if (item.labelId == row.labelId) {
        addAction.value = true;
        break;
      }
    }
  }

  if (addAction.value) {
    selecteddiseaseLabelList.value.push(row);
  } else {
    let tList = ref<DiseaseLabelVO[]>([]);
    selecteddiseaseLabelList.value.forEach(item => {
      if (item.labelId != row.labelId) {
        tList.value.push(item);
      }
    })
    selecteddiseaseLabelList.value = tList.value;
  }
}

/** 多选框选中数据 */
const handleSelectionChange2 = (selection: DiseaseLabelVO[]) => {
  if (loading.value) {
    let tJson = ref({})
    selecteddiseaseLabelList2.value.forEach(item => {
      tJson.value[item.labelId] = true;
    })

    diseaseLabelList.value.forEach(item => {
      if (tJson.value[item.labelId]) {
        diseaseLabelRef2.value.toggleRowSelection(item, true);
      }
    })
    loading.value = false;
  }
}

/** 多选框选中数据 */
const handleSelectAllChange2 = (selection: DiseaseLabelVO[]) => {
  if (selection.length == 0) {
    selecteddiseaseLabelList2.value = [];
  } else {
    let tJson = ref({})
    selecteddiseaseLabelList2.value.forEach(item => {
      tJson.value[item.labelId] = true;
    })

    selection.forEach(item => {
      if (!tJson.value[item.labelId]) {
        selecteddiseaseLabelList2.value.push(item);
      }
    })
  }
}

const handleSelectChange2 = (selection: DiseaseLabelVO[], row: DiseaseLabelVO) => {
  let addAction = ref<boolean>(false);
  if (selection.length > 0) {
    for (let item of selection) {
      if (item.labelId == row.labelId) {
        addAction.value = true;
        break;
      }
    }
  }

  if (addAction.value) {
    selecteddiseaseLabelList2.value.push(row);
  } else {
    let tList = ref<DiseaseLabelVO[]>([]);
    selecteddiseaseLabelList2.value.forEach(item => {
      if (item.labelId != row.labelId) {
        tList.value.push(item);
      }
    })
    selecteddiseaseLabelList2.value = tList.value;
  }
}


/** 多选框选中数据 */
const handleSelectAllChange3 = (selection: FoodIngredientVO[]) => {
  if (selection.length == 0) {
    selectedIngredientList.value = [];
  } else {
    let tJson = ref({})
    selectedIngredientList.value.forEach(item => {
      tJson.value[item.foodIngredientId] = true;
    })

    selection.forEach(item => {
      if (!tJson.value[item.foodIngredientId]) {
        selectedIngredientList.value.push(item);
      }
    })
  }
}

const handleSelectChange3 = (selection: FoodIngredientVO[], row: FoodIngredientVO) => {
  let addAction = ref<boolean>(false);
  if (selection.length > 0) {
    for (let item of selection) {
      if (item.foodIngredientId == row.foodIngredientId) {
        addAction.value = true;
        break;
      }
    }
  }

  if (addAction.value) {
    selectedIngredientList.value.push(row);
  } else {
    let tList = ref<FoodIngredientVO[]>([]);
    selectedIngredientList.value.forEach(item => {
      if (item.foodIngredientId != row.foodIngredientId) {
        tList.value.push(item);
      }
    })
    selectedIngredientList.value = tList.value;
  }
}




const handleSelectedDelete = (row?: DiseaseLabelVO[]) => {
  if (row) {
    const tList = ref<DiseaseLabelVO[]>([]);
    selecteddiseaseLabelList.value.forEach(item => {
      if (item.labelId != row.labelId) {
        tList.value.push(item);
      } else {
        diseaseLabelRef.value.toggleRowSelection(item, false);
      }
    });
    selecteddiseaseLabelList.value = tList.value;
  }
}

const handleSelectedDelete2 = (row?: DiseaseLabelVO[]) => {
  if (row) {
    const tList = ref<DiseaseLabelVO[]>([]);
    selecteddiseaseLabelList2.value.forEach(item => {
      if (item.labelId != row.labelId) {
        tList.value.push(item);
      } else {
        diseaseLabelRef2.value.toggleRowSelection(item, false);
      }
    });
    selecteddiseaseLabelList2.value = tList.value;
    selecteddiseaseLabelListBak2.value = tList.value;
  }
}



/** 查询食谱管理列表 */
const getRecipeCategoryList = async () => {
  const queryParams = ref<RecipeCategoryQuery>({
    pageNum: 1,
    pageSize: -1,
  })
  const res = await listRecipeCategory(queryParams.value);
  recipeCategoryList.value = res.rows;
}

/** 查询科室下拉树结构 */
const getDeptTree = async () => {
  const res = await api.deptTreeSelect();
  enabledDeptOptions.value = res.data;
};

/** 查询疾病/部位标签列表 */
const getDiseaseLabelList = async () => {
  const res = await listDiseaseLabel(diseaseLabelQuery.value);
  diseaseLabelList.value = res.rows;
  total.value = res.total;
  loading.value = true;
}

const changeTag = async (tagVal: string) => {
  diseaseLabelQuery.value.category = tagVal;
  await getDiseaseLabelList();
}

const openAvoidDiseaseDialog = async () => {
  dialog.visible = true;
  dialog.title = '添加疾病标签';
  diseaseLabelQuery.value.labelCode = ''
  diseaseLabelQuery.value.category = disease_label.value[0].value;
  await getDiseaseLabelList();
  if (selecteddiseaseLabelListBak.value && selecteddiseaseLabelListBak.value.length > 0) {
    let dataMap = ref({});
    selecteddiseaseLabelListBak.value.forEach(item => {
      dataMap[item.labelId] = true;
    });

    diseaseLabelList.value.forEach(item => {
      if (dataMap[item.labelId]) {
        diseaseLabelRef.value.toggleRowSelection(item, true);
      }
    });
  }
}

const openAvoidDiseaseDialog2 = async () => {
  dialog2.visible = true;
  dialog2.title = '添加疾病标签';
  diseaseLabelQuery.value.labelCode = ''
  diseaseLabelQuery.value.category = disease_label.value[disease_label.value.length - 1].value;
  await getDiseaseLabelList();
  if (selecteddiseaseLabelListBak2.value && selecteddiseaseLabelListBak2.value.length > 0) {
    let dataMap = ref({});
    selecteddiseaseLabelListBak2.value.forEach(item => {
      dataMap[item.labelId] = true;
    });

    diseaseLabelList.value.forEach(item => {
      if (dataMap[item.labelId]) {
        diseaseLabelRef2.value.toggleRowSelection(item, true);
      }
    });
  }
}


const handleSelectedconfirm = async () => {
  dialog.visible = false;
  form.value.suitableDisease = selecteddiseaseLabelList.value.map(v => v.labelName).join(',')
  selecteddiseaseLabelListBak.value = selecteddiseaseLabelList.value;
}

const handleSelectedconfirm2 = async () => {
  dialog2.visible = false;
  form.value.avoidDisease = selecteddiseaseLabelList2.value.map(v => v.labelName).join(',')
  selecteddiseaseLabelListBak2.value = selecteddiseaseLabelList2.value;
}

const handleSelectedconfirm3 = async () => {
  dialog3.visible = false;
  selectedIngredientListBak.value = selectedIngredientList.value;
  selectedIngredientList.value = [];
  foodIngredienRef.value?.clearSelection();
}

const addDiseaseLabelDialog = async () => {
  diseaseLabelDialog.visible = true;
  diseaseLabelDialog.title = '新增疾病标签';
  diseaseLabelFormRef.value?.resetFields();
}


const diseaseLabelCancel = async () => {
  diseaseLabelDialog.visible = false;
  diseaseLabelFormRef.value?.resetFields();
}

const diseaseLabelSubmitForm = async () => {
  diseaseLabelFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (diseaseLabelFormData.value.labelId) {
        await updateDiseaseLabel(diseaseLabelFormData.value).finally(() => buttonLoading.value = false);
      } else {
        const res = await addDiseaseLabel(diseaseLabelFormData.value).finally(() => buttonLoading.value = false);
        diseaseLabelFormData.value.labelId = res.data;
        const vo = ref<DiseaseLabelVO>({
          labelId: undefined,
          labelName: undefined,
          category: undefined,
          labelCode: undefined,
          status: undefined,
          categoryName: undefined,
        });
        Object.assign(vo.value, diseaseLabelFormData.value);

        disease_label.value.forEach(item => {
          if (diseaseLabelFormData.value.category == item.value) {
            vo.value.categoryName = item.label;
          }
        })

        selecteddiseaseLabelList.value.push(vo.value);
        diseaseLabelList.value.push(vo.value);
        selecteddiseaseLabelList.value.forEach(item => {
          diseaseLabelRef.value.toggleRowSelection(item, true);
        });
      }
      proxy?.$modal.msgSuccess("操作成功");
      diseaseLabelDialog.visible = false;
    }
  });
}


const addDiseaseLabelDialog2 = async () => {
  diseaseLabelDialog2.visible = true;
  diseaseLabelDialog2.title = '新增疾病标签';
  diseaseLabelFormRef2.value?.resetFields();
}


const diseaseLabelCancel2 = async () => {
  diseaseLabelDialog2.visible = false;
  diseaseLabelFormRef2.value?.resetFields();
}

const diseaseLabelSubmitForm2 = async () => {
  diseaseLabelFormRef2.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (diseaseLabelFormData2.value.labelId) {
        await updateDiseaseLabel(diseaseLabelFormData2.value).finally(() => buttonLoading.value = false);
      } else {
        const res = await addDiseaseLabel(diseaseLabelFormData2.value).finally(() => buttonLoading.value = false);
        diseaseLabelFormData2.value.labelId = res.data;
        const vo = ref<DiseaseLabelVO>({
          labelId: undefined,
          labelName: undefined,
          category: undefined,
          labelCode: undefined,
          status: undefined,
          categoryName: undefined,
        });
        Object.assign(vo.value, diseaseLabelFormData2.value);

        disease_label.value.forEach(item => {
          if (diseaseLabelFormData2.value.category == item.value) {
            vo.value.categoryName = item.label;
          }
        })

        selecteddiseaseLabelList2.value.push(vo.value);
        diseaseLabelList2.value.push(vo.value);
        selecteddiseaseLabelList2.value.forEach(item => {
          diseaseLabelRef2.value.toggleRowSelection(item, true);
        });
      }
      proxy?.$modal.msgSuccess("操作成功");
      diseaseLabelDialog2.visible = false;
    }
  });
}


/** 查询食材管理列表 */
const getListFoodIngredient = async () => {
  const res = await listFoodIngredient(foodIngredientQuery.value);
  foodIngredientList.value = res.rows;
  totalFood.value = res.total;
  if (res.rows && res.rows.length > 0 && selectedIngredientList.value && selectedIngredientList.value.length > 0) {
    setTimeout(() => {
      let tJson = ref({})
      selectedIngredientList.value.forEach(item => {
        tJson.value[item.foodIngredientId] = true;
      })

      foodIngredientList.value.forEach(item => {
        if (tJson.value[item.foodIngredientId]) {
          foodIngredienRef.value.toggleRowSelection(item, true);
        }
      })
    }, 500);
  }
}

const handleNodeClick = async (data: FoodCategoryVO) => {
  if (foodIngredientQuery.value.foodCategoryId != data.foodCategoryId) {
    foodIngredientQuery.value.foodCategoryId = data.foodCategoryId;
    await getListFoodIngredient();
  }
}

const openAddFoodDialog = async () => {
  dialog3.visible = true;
  dialog3.title = '添加食材';
  foodIngredientQuery.value.name = undefined;
  foodIngredientQuery.value.foodCategoryId = undefined;
  await getListTree();
  await getListFoodIngredient();

  if (selectedIngredientListBak.value && selectedIngredientListBak.value.length > 0) {
    let dataMap = ref({});
    selectedIngredientListBak.value.forEach(item => {
      dataMap[item.foodIngredientId] = true;
    });

    foodIngredientList.value.forEach(item => {
      if (dataMap[item.foodIngredientId]) {
        foodIngredienRef.value.toggleRowSelection(item, true);
      }
    });
  }

}

const editFoodquantity = async (data: FoodIngredientVO) => {
  let quantity = Number(data.quantity) / 100;
  let calories = Number(data.calories);
  data.caloriesForInput = Math.floor(quantity * calories * 100) / 100;

  let qSum = ref(0.0);
  let cSum = ref(0.0);
  selectedIngredientListBak.value.forEach(item => {
    if (item.caloriesForInput) {
      cSum.value += item.caloriesForInput;
    }
    if (item.quantity) {
      qSum.value += Number(item.quantity);
    }
  });
  caloriesSum.value = (Math.floor(cSum.value * 100) / 100).toString();
  quantitySum.value = (Math.floor(qSum.value * 100) / 100).toString();
}

const deleteFoodquantity = async (data: FoodIngredientVO) => {
  let tList = ref<FoodIngredientVO[]>([]);
  selectedIngredientListBak.value.forEach(item => {
    if (data.foodIngredientId != item.foodIngredientId) {
      tList.value.push(item);
    }
  });
  selectedIngredientListBak.value = tList.value
  selectedIngredientList.value = [];
  foodIngredienRef.value?.clearSelection();
}

/** 提交按钮 */
const submitForm = () => {
  foodIngredientFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!selectedIngredientListBak.value || selectedIngredientListBak.value.length == 0) {
        proxy?.$modal.msgError("请先添加【食材组成】部分的信息");
        return;
      }
      buttonLoading.value = true;
      let params = ref<RecipeForm>({});
      Object.assign(params.value, form.value);
      params.value.suitableDept = form.value.suitableDeptList.join(',')
      params.value.suitableDisease = selecteddiseaseLabelList.value.map(v => v.labelId).join(',')
      params.value.avoidDisease = selecteddiseaseLabelList2.value.map(v => v.labelId).join(',')
      params.value.mealTime = params.value.mealTimes.join(',')
      params.value.foodList = [];

      for (let item of selectedIngredientListBak.value) {
        let dataJSon = {};
        dataJSon['foodIngredientId'] = item.foodIngredientId;
        dataJSon['quantity'] = item.quantity;
        if (!item.quantity) {
          buttonLoading.value = false;
          proxy?.$modal.msgError("【食材用量】不能为空");
          return;
        }
        dataJSon['calories'] = item.caloriesForInput;
        dataJSon['remark'] = item.remark;
        params.value.foodList.push(dataJSon);
      }

      if (form.value.recipeId) {
        await updateRecipe(params.value).finally(() => buttonLoading.value = false);
      } else {
        await addRecipe(params.value).then(res => {
          form.value.recipeId = res.data;
        }).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      close();
    }
  });

}

const getList = async () => {
  const recipeId = route.params && route.params.id;
  const vRecipeId = route.params && route.params.vid;
  let id = undefined;
  if (vRecipeId) {
    isView.value = true;
    id = vRecipeId;
      } else {
    isView.value = false;
    id = recipeId;
  }

  if (id && id != '0') {
    dataLoading.value = true;
    const res = await getRecipe(id as string);
    Object.assign(form.value, res.data);

    if (res.data.suitableDept && res.data.suitableDept.length > 0) {
      form.value.suitableDeptList = res.data.suitableDept.split(',');
    }
    if (res.data.avoidDiseaseList && res.data.avoidDiseaseList.length > 0) {
      selecteddiseaseLabelListBak2.value = res.data.avoidDiseaseList;
      selecteddiseaseLabelList2.value = res.data.avoidDiseaseList;
      form.value.avoidDisease = selecteddiseaseLabelList2.value.map(v => v.labelName).join(',')
    }
    if (res.data.suitableDiseaseList && res.data.suitableDiseaseList.length > 0) {
      selecteddiseaseLabelListBak.value = res.data.suitableDiseaseList;
      selecteddiseaseLabelList.value = res.data.suitableDiseaseList;
      form.value.suitableDisease = selecteddiseaseLabelList.value.map(v => v.labelName).join(',')
    }
    if (res.data.mealTime && res.data.mealTime.length > 0) {
      form.value.mealTimes = res.data.mealTime.split(',')
    }
    if (res.data.foodList && res.data.foodList.length > 0) {
      selectedIngredientListBak.value = res.data.foodList;
      let qSum = ref(0.0);
      let cSum = ref(0.0);
      selectedIngredientListBak.value.forEach(item => {
        let quantity = Number(item.quantity) / 100;
        let calories = Number(item.calories);
        item.caloriesForInput = Math.floor(quantity * calories * 100) / 100;

        if (item.caloriesForInput) {
          cSum.value += item.caloriesForInput;
        }
        if (item.quantity) {
          qSum.value += Number(item.quantity);
        }
      });
      caloriesSum.value = (Math.floor(cSum.value * 100) / 100).toString();
      quantitySum.value = (Math.floor(qSum.value * 100) / 100).toString();
    }

    dataLoading.value = false;
  }
}

const handleMenumSelect = async (key: string, keyPath: string[]) => {
  currentIndex.value = key.toString()
}

const nutrientAnalysisLeftData = async () => {
  let dataTemplate = JSON.stringify({
    nutrientName: '',
    nutrientQuantity: 0,
    nutrientRatio: 0,
    nutrientRefVal: ''
  })

  leftList.value=[];
  let protein = ref<FoodIngredientVO>();
  let fat = ref<FoodIngredientVO>();
  let carbohydrate = ref<FoodIngredientVO>();
  protein.value = JSON.parse(dataTemplate);
  fat.value = JSON.parse(dataTemplate);
  carbohydrate.value = JSON.parse(dataTemplate);
  leftList.value.push(protein.value);
  leftList.value.push(fat.value);
  leftList.value.push(carbohydrate.value);

  let nrJson = {};
  nutrient_reference.value.forEach(nr => {
    nrJson[nr.label] = nr;
  })
  protein.value.nutrientRefVal = nrJson['nutrient_protein'].value;
  fat.value.nutrientRefVal = nrJson['nutrient_fat'].value;
  carbohydrate.value.nutrientRefVal = nrJson['nutrient_carbohydrate'].value;
  protein.value.nutrientName = '蛋白质';
  fat.value.nutrientName = '脂肪';
  carbohydrate.value.nutrientName = '碳水化合物';

  let sum: number = 0.0; 

  selectedIngredientListBak.value.forEach(item => {
    protein.value.nutrientQuantity += Number(item.protein);
    fat.value.nutrientQuantity += Number(item.fat);
    carbohydrate.value.nutrientQuantity += Number(item.carbohydrate);
    sum += protein.value.nutrientQuantity + fat.value.nutrientQuantity + carbohydrate.value.nutrientQuantity;
    leftCalories.value += Number(item.caloriesForInput);
  })  

  protein.value.nutrientRatio = (sum > 0 ? (protein.value.nutrientQuantity / sum * 100).toFixed(2) : '0.00') + '%';
  fat.value.nutrientRatio = (sum > 0 ? (fat.value.nutrientQuantity / sum * 100).toFixed(2) : '0.00') + '%';
  carbohydrate.value.nutrientRatio = (sum > 0 ? (carbohydrate.value.nutrientQuantity / sum * 100).toFixed(2) : '0.00') + '%';
 
  pieOption.value.legend.data = []
  pieOption.value.series[0].data = []
  leftList.value.forEach(item => {
    pieOption.value.series[0].data.push({ value: Number(item.nutrientRatio.replace('%', '')), name: item.nutrientName + ' ' + item.nutrientRatio })
    pieOption.value.legend.data.push(item.nutrientName + ' ' + item.nutrientRatio);
  });

  return nrJson['nutritional_data_analysis'].remark
}


const nutrientAnalysisRightData = async (jsonStr:string) => {
  rightList.value=[];
  if(selectedIngredientListBak.value.length<1){
    return; 
  }
  
  let nutritionalDataAnalysis =  JSON.parse(jsonStr);
  nutritionalDataAnalysis.forEach((na:any) => {
    let showData={}
    selectedIngredientListBak.value.forEach(item => {
      let quantity = Number(item.quantity?item.quantity:0) / 100;
      if(!showData['nutrientName']){
        showData['nutrientUnit'] =na.unit;
        showData['nutrientName'] = na.remark;
        showData['nutrientQuantity'] = item[na.name]?Number(item[na.name])*quantity/100 : 0;
      } else{
        showData['nutrientQuantity'] = (item[na.name]?Number(item[na.name])*quantity/100:0)+showData['nutrientQuantity'];
      }       
  });
   
   rightList.value.push(JSON.parse(JSON.stringify(showData)));
  }); 
  
  rightList.value.forEach(item=>{
    if(item.nutrientQuantity>0){
      item.nutrientQuantity=Math.floor(item.nutrientQuantity*10000)/10000
    }
  })
  
}

const nutrientAnalysisData = async () => {
  let jsonStr:string=await nutrientAnalysisLeftData();
  await nutrientAnalysisRightData(jsonStr);  
}

const showNutrientAnalysisDialog = async () => {
  dialog4.visible = true;
  dialog4.title = '营养数据分析';
  nutrientAnalysisData();
}


onMounted(() => {
  getDiseaseLabelList()
  getDeptTree();
  getRecipeCategoryList();
  getList();
});
</script>

<style lang="scss" scoped>
.card-footer {
  z-index: 99;
  bottom: 0px;
  left: calc(var(--left-menu-max-width) + var(--app-content-padding));
  right: 0px;
  height: 90px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.diagnosis-tag {
  border-left: 1px solid #409EFF;  
  border-top: 1px solid #409EFF;  
  border-bottom: 1px solid #409EFF;  
  padding: 8px 8px;   
  color: #409EFF;
  background: #f4f8ff;
  display: inline-block;
  width: 33.3%;
  margin-bottom: 10px;
  text-align: center;
  vertical-align: middle;
}

.diagnosis-tag:last-child {  
  border-right: 1px solid #409EFF; 
}

.diagnosisActive {
  background: #409EFF;
  color: #fff;
}

.el-pagination__sizes {
  width: 100px;
}

.chart-center {
  display: flex;
  flex-direction: column;
  /* 垂直方向排列 */
  justify-content: center;
  /* 垂直居中 */
  align-items: center;
  /* 水平居中 */
  height: 100%;
  /* 父容器需有高度 */
  min-height: 300px;
  /* 可根据需要设置 */
}
</style>
