<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-select v-model="list.main.query.baseUnit" class="filter-item" size="mini" placeholder="食物类型" style="width:150px;margin-right:5px;" clearable>
        <el-option label="是" :value="true" />
        <el-option label="否" :value="false" />
      </el-select>
      <el-select v-model="list.main.query.baseUnit" class="filter-item" size="mini" placeholder="食物类别" style="width:150px;margin-right:5px;" clearable>
        <el-option label="是" :value="true" />
        <el-option label="否" :value="false" />
      </el-select>
      <el-input v-model="list.main.query.name" class="filter-item" size="mini" placeholder="名称" style="width:150px;margin-right:5px;" clearable />
      <el-input v-model="list.main.query.enName" class="filter-item" size="mini" placeholder="英文名称" style="width:150px;margin-right:5px;" clearable />
      <el-select v-model="list.main.query.baseUnit" class="filter-item" size="mini" placeholder="状态" style="width:150px;margin-right:5px;" clearable>
        <el-option label="是" :value="true" />
        <el-option label="否" :value="false" />
      </el-select> -->
      <el-button class="filter-item" size="mini" type="primary" @click="M.list()">查询</el-button>
      <el-button class="filter-item" size="mini" @click="() => {M.reset({ data: { page: 1, limit: list.main.query.limit } })}">重置</el-button>

      <div style="float:right;">
        <el-button class="filter-item" size="mini" type="success" style="margin-right:15px;" @click="create">新增</el-button>
      </div>
    </div>
    <el-table v-loading="list.main.loading" :data="list.main.list" border fit highlight-current-row style="width:100%" :max-height="maxHeight">
      <!-- <el-table-column width="50" header-align="center" label="权重">
        <template slot-scope="{row}">
          <span>{{ row.sortOrder }}</span>
        </template>
      </el-table-column> -->
      <el-table-column width="70" align="center" label="图片">
        <template slot-scope="{row}">
          <el-image v-if="row.mainImage" style="width:50px;height:50px;" :src="row.mainImage" fit="contain" />
        </template>
      </el-table-column>
      <el-table-column min-width="150" header-align="center" label="名称">
        <template slot-scope="{row}">
          <el-tag v-if="!!row.typeName" size="mini" effect="plain">{{ row.typeName }}</el-tag><span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="180" header-align="center" label="英文名称">
        <template slot-scope="{row}">
          <span>{{ row.enName }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80" header-align="center" align="right" label="可食部(%)">
        <template slot-scope="{row}">
          <span v-if="row.ep>0">{{ row.ep }}%</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column width="80" header-align="center" align="right" label="GI">
        <template slot-scope="{row}">
          <span>{{ row.gi }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80" header-align="center" align="right" label="GL">
        <template slot-scope="{row}">
          <span>{{ row.gl }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100" align="center" label="来源">
        <template slot-scope="{row}">
          <span>{{ row.source }}</span>
        </template>
      </el-table-column>
      <el-table-column width="60" align="center" label="状态">
        <template slot-scope="{row}">
          <span v-if="row.shelfStatus=='ONLINE'" style="color:green;">上架</span>
          <span v-else style="color:gray;">下架</span>
        </template>
      </el-table-column>
      <el-table-column width="80" align="center" label="创建人">
        <template slot-scope="{row}">
          <span>{{ row.userName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column width="140" align="center" label="创建时间">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column width="140" align="center" label="更新时间">
        <template slot-scope="{row}">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column width="60" align="center" label="操作" fixed="right">
        <template slot-scope="{row}">
          <i class="el-icon-edit" style="cursor:pointer;color:#999999;margin-right:5px;" @click="edit(row)"></i>
          &nbsp;&nbsp;
          <i class="el-icon-delete" style="cursor:pointer;color:#999999;m"></i>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="list.main.total>0" :total="list.main.total" :page.sync="list.main.query.page" :limit.sync="list.main.query.limit" @pagination="M.list()" />

    <el-dialog :title="dlg.form.title" :visible.sync="dlg.form.visible" width="95%" top="3vh">
      <el-form ref="form" :rules="dlg.form.rules" :model="dlg.form.data" size="mini" label-position="right" label-width="100px">
        <el-tabs v-model="dlg.form.infoTab" @tab-click="foodInfoTabClick">
          <el-tab-pane label="食物基本信息" name="base">
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="dlg.form.data.name" placeholder="请输入食物名称，不能重复" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="主/辅料" prop="type">
                  <el-select v-model="dlg.form.data.type" class="filter-item" size="mini" placeholder="请选择主/辅料" style="width:100%;">
                    <el-option label="主料" value="MAIN" />
                    <el-option label="辅料" value="SUB" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="食物形态">
                  <el-select v-model="dlg.form.data.som" class="filter-item" size="mini" placeholder="请选择食物形态" style="width:70%;">
                    <el-option label="固态" value="SOLID" />
                    <el-option label="液态" value="LIQUID" />
                  </el-select>
                  <el-checkbox v-model="dlg.form.data.isGranular" style="float:right;">颗粒状</el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="食物类别">
                  <el-input v-model="dlg.form.data.categoryId" placeholder="请选择食物类别" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="可食部">
                  <el-input v-model="dlg.form.data.ep" :min="0" :max="100" placeholder="可食部(0~100%)">
                    <span slot="append">%</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="[计算]可食部">
                  <el-input v-model="dlg.form.data.calcEp" :min="0" :max="100" placeholder="计算用可食部(0~100%)">
                    <span slot="append">%</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="GI">
                  <el-input v-model="dlg.form.data.gi" placeholder="请输入GI" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="GL">
                  <el-input v-model="dlg.form.data.gl" placeholder="请输入GL" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="密度">
                  <el-input v-model="dlg.form.data.densityVolumeAmt" placeholder="体积" style="width:60px;" />
                  <DataSelect
                    url="/api/volume-units"
                    placeholder="体积单位"
                    :value.sync="dlg.form.data.densityVolumeUnitId"
                    :label.sync="dlg.form.data.densityVolumeUnit"
                    width="130px;margin-left:1px;"
                  />
                  <span style="color:red;font-size:14px;font-weight:700;">&nbsp;=&nbsp;</span>
                  <el-input v-model="dlg.form.data.densityAmt" placeholder="质量" style="width:60px;" />
                  <DataSelect
                    url="/api/mass-units"
                    placeholder="质量单位"
                    :value.sync="dlg.form.data.densityUnitId"
                    :label.sync="dlg.form.data.densityUnit"
                    width="130px;margin-left:1px;"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="堆密度">
                  <el-input v-model="dlg.form.data.bulkDensityVolumeAmt" placeholder="体积" style="width:60px;" />
                  <DataSelect
                    url="/api/volume-units"
                    placeholder="体积单位"
                    :value.sync="dlg.form.data.bulkDensityVolumeUnitId"
                    :label.sync="dlg.form.data.bulkDensityVolumeUnit"
                    width="130px;margin-left:1px;"
                  />
                  <span style="color:red;font-size:14px;font-weight:700;">&nbsp;=&nbsp;</span>
                  <el-input v-model="dlg.form.data.bulkDensityAmt" placeholder="堆密度" style="width:60px;" />
                  <DataSelect
                    url="/api/units"
                    placeholder="堆密度单位"
                    :value.sync="dlg.form.data.bulkDensityUnitId"
                    :label.sync="dlg.form.data.bulkDensityUnit"
                    width="130px;margin-left:1px;"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="[计算]密度">
                  <el-input v-model="dlg.form.data.calcDensityVolumeAmt" placeholder="体积" style="width:60px;" />
                  <DataSelect
                    url="/api/volume-units"
                    placeholder="体积单位"
                    :value.sync="dlg.form.data.calcDensityVolumeUnitId"
                    :label.sync="dlg.form.data.calcDensityVolumeUnit"
                    width="130px;margin-left:1px;"
                  />
                  <span style="color:red;font-size:14px;font-weight:700;">&nbsp;=&nbsp;</span>
                  <el-input v-model="dlg.form.data.calcDensityAmt" placeholder="质量" style="width:60px;" />
                  <DataSelect
                    url="/api/mass-units"
                    placeholder="质量单位"
                    :value.sync="dlg.form.data.calcDensityUnitId"
                    :label.sync="dlg.form.data.calcDensityUnit"
                    width="130px;margin-left:1px;"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="描述">
              <el-input v-model="dlg.form.data.code" type="textarea" rows="3" placeholder="请输入单位编码，可为空，但不能重复" />
            </el-form-item>
            <el-form-item label="食物图">
            </el-form-item>
            <el-form-item label="营养素图">
            </el-form-item>
            <el-form-item label="其他图">
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="规格" name="modifier">
            <div style="margin-bottom:5px;">
              <el-button size="mini" type="primary" plain @click="addModifier(dlg.form.data)">添加</el-button>
            </div>
            <el-table :data="dlg.form.data.modifiers" :show-header="false" border fit highlight-current-row style="width:100%">
              <el-table-column type="index" width="50" align="center" />
              <el-table-column>
                <template slot-scope="{row}">
                  <span v-if="row._edit">
                    <el-input v-model="row.name" placeholder="规格名称" style="width:130px;margin-right:5px;" @change="modifierUnitChange" />
                    <DataSelect
                      url="/api/units"
                      placeholder="规格单位"
                      :value.sync="row.unitId"
                      :label.sync="row.unitName"
                      width="100px"
                      :allowCreate="true"
                      @select="modifierUnitChange"
                    />
                    [
                      <span style="color:blue;font-size:13px;">&nbsp;规格转换:&nbsp;</span>
                      <el-input v-model="row.toModifierInput" placeholder="数量" style="width:60px;" />
                      <span>{{ row.key || '' }}</span>
                      <span style="color:red;font-size:14px;font-weight:700;">&nbsp;=&nbsp;</span>
                      <el-input v-model="row.toModifierAmt" placeholder="数量" style="width:60px;margin-right:10px;" />
                      <el-select v-model="row.toModifierName" class="filter-item" placeholder="规格单位" style="width:120px" clearable>
                        <el-option v-for="opt in dlg.form.modifierUnitOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
                      </el-select>
                    ]
                    [
                      <span style="color:blue;font-size:13px;">&nbsp;标准单位转换:&nbsp;</span>
                      <el-input v-model="row.stdMeasureInput" placeholder="数量" style="width:60px;" />
                      <span>{{ row.key || '' }}</span>
                      <span style="color:red;font-size:14px;font-weight:700;">&nbsp;=&nbsp;</span>
                      <el-input v-model="row.stdMeasureAmt" placeholder="数量" style="width:60px;margin-right:10px;" />
                      <DataSelect
                        url="/api/units"
                        placeholder="标准单位"
                        :value.sync="row.stdMeasureUnitId"
                        :label.sync="row.stdMeasureUnit"
                        width="90px"
                      />
                    ]
                    [
                      <span style="color:blue;font-size:13px;">&nbsp;推荐量:&nbsp;</span>
                      <el-input v-model="row.inInit" placeholder="数量" style="width:60px;" />
                      <DataSelect
                        url="/api/units"
                        placeholder="推荐量单位"
                        :value.sync="row.inInitUnitId"
                        :label.sync="row.inInitUnit"
                        :initOptions="dlg.form.modifierUnitOptions"
                        width="90px"
                      />
                    ]

                    <br>
                    <el-checkbox v-model="row.isBiteSized" label='isBiteSized'></el-checkbox>
                    <el-checkbox v-model="row.isServing" label='isServing'></el-checkbox>
                    <el-checkbox v-model="row.isPrepackaged" label='isPrepackaged'></el-checkbox>
                    <el-checkbox v-model="row.isRealSku" label='isRealSku'></el-checkbox> 

                  </span>
                  <span v-else>
                    -
                  </span>

                </template>
              </el-table-column>
              <el-table-column width="90" align="center">
                <template slot-scope="{$index}">
                  <i class="el-icon-delete" style="cursor:pointer;color:#999999;margin-right:5px;" @click="fn.remove(dlg.form.data.modifiers, $index)"></i>
                  &nbsp;&nbsp;
                  <i class="el-icon-top" style="cursor:pointer;color:#999999;margin-right:5px;" @click="fn.moveUp(dlg.form.data.modifiers, $index)"></i>
                  &nbsp;&nbsp;
                  <i class="el-icon-bottom" style="cursor:pointer;color:#999999;" @click="fn.moveDown(dlg.form.data.modifiers, $index)"></i>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="营养素" name="nutrient">
            <div style="margin-bottom:5px;">
              <span>
                <el-button size="mini" type="primary" plain @click="addNutrient(dlg.form.data)">添加</el-button>
              </span>
              <el-select v-model="dlg.form.selectedNutrientTemplate" class="filter-item" style="margin-left: 10%; display: float; margin-right: 0.5%" v-on:input.native="getNutrienttemplateList($event, dlg.form)"  filterable placeholder="请输入检索词">
                <el-option v-for="opt in dlg.form.nutrientTemplateOptions" :key="opt.id" :label="opt.name" :value="opt.name" />
              </el-select>
              <el-button size="mini" type="primary" plain @click="importNutrientTemplate()">导入营养素模版</el-button>

            </div>
            <el-table :data="dlg.form.data.nutrients" :show-header="false" border fit highlight-current-row style="width:100%">
              <el-table-column type="index" width="50" align="center" />
              <el-table-column>
                <template slot-scope="{row}">
                  <span v-if="row._edit">
                    <DataSelect
                      url="/api/nutrients"
                      placeholder="请选择营养素"
                      width="130px;margin-right:5px;"
                      :value.sync="row.nutrientId"
                      :label.sync="row.nutrientName"
                      @select="(nutrient) => nutrientSelect(nutrient, row)"
                    />
                    <el-select v-model="row.nvMeasureMode" size="mini" placeholder="计量" style="width:80px;margin-right:5px;">
                      <el-option label="值" value="VALUE" />
                      <el-option label="范围" value="RANGE" />
                      <el-option label="误差" value="ADJUST" />
                    </el-select>
                    <span style="color:red;font-size:15px;font-weight:700;">（</span>
                    <span v-if="row.nvMeasureMode=='VALUE'">
                      <el-input v-model="row.nv" placeholder="取值" style="width:70px;margin-right:10px;" />
                    </span>
                    <span v-else-if="row.nvMeasureMode=='RANGE'">
                      <el-input v-model="row.nvMin" placeholder="最小值" style="width:70px;margin-right:10px;" />
                      -
                      <el-input v-model="row.nvMax" placeholder="最大值" style="width:70px;margin-right:10px;" />
                    </span>
                    <span v-else-if="row.nvMeasureMode=='ADJUST'">
                      <el-input v-model="row.nv" placeholder="取值" style="width:70px;margin-right:10px;" />
                      <el-input v-model="row.nv_adjust" placeholder="误差" style="width:80px;margin-right:10px;">
                        <span slot="prepend">±</span>
                      </el-input>
                    </span>
                    <el-select v-model="row.nvUnitId" placeholder="营养素单位" style="width:100px" clearable>
                      <el-option v-if="!!row.nvUnitId && row._nutrientUnitOptions && !row._nutrientUnitOptions.find(v => v.value == row.nvUnitId)" :key="row.nvUnitId" :label="row.nvUnit" :value="row.nvUnitId" />
                      <el-option v-for="opt in row._nutrientUnitOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
                      <el-option v-for="opt in dlg.form.data.nutrients" :key="opt.nvUnitId" :label="opt.nvUnit" :value="opt.nvUnitId" />
                    </el-select>
                    <span style="color:red;font-weight:700;">&nbsp;/&nbsp;</span>
                    <el-input v-model="row.nvSpec" placeholder="nv_spec" style="width:70px;margin-right:10px;" />
                    <DataSelect
                      url="/api/units"
                      placeholder="nv_spec单位"
                      :value.sync="row.nvSpecUnitId"
                      :label.sync="row.nvSpecUnit"
                      width="110px"
                      :allowCreate="true"
                      :initOptions="dlg.form.modifierUnitOptions"
                    />
                    <span style="color:red;font-size:15px;font-weight:700;">）</span>
                    <!-- [
                    <span style="color:green;font-weight:700;">1</span>&nbsp;<span style="color:red">{{ row.nvSpecUnit }}</span>
                    &nbsp;*&nbsp;
                    <el-input v-model="row.cfNvUnitToBaseUnit" style="width:80px;margin-right:5px;" />
                    =&nbsp;*&nbsp; 1 {{ row.nutrient && row.nutrient.baseUnitName || '基础单位' }}
                    ] -->
                  </span>
                  <span v-else>
                  </span>
                </template>
              </el-table-column>
              <el-table-column width="90" align="center">
                <template slot-scope="{$index}">
                  <i class="el-icon-delete" style="cursor:pointer;color:#999999;margin-right:5px;" @click="fn.remove(dlg.form.data.nutrients, $index)"></i>
                  &nbsp;&nbsp;
                  <i class="el-icon-top" style="cursor:pointer;color:#999999;margin-right:5px;" @click="fn.moveUp(dlg.form.data.nutrients, $index)"></i>
                  &nbsp;&nbsp;
                  <i class="el-icon-bottom" style="cursor:pointer;color:#999999;" @click="fn.moveDown(dlg.form.data.nutrients, $index)"></i>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="CF" name="cf">
            <el-tag v-if="dlg.form.data.calcDensityAmt>0&&dlg.form.data.calcDensityVolumeAmt>0" style="margin-bottom:5px;">
              {{ dlg.form.data.calcDensityAmt }}{{ dlg.form.data.calcDensityUnit }}={{ dlg.form.data.calcDensityVolumeAmt }}{{ dlg.form.data.calcDensityVolumeUnit }}
            </el-tag>
            <el-table :data="dlg.form.data.cfs" border fit highlight-current-row style="width:100%">
              <el-table-column type="index" width="50" align="center" />
              <el-table-column min-width="180" header-align="center" label="源单位">
                <template slot-scope="{row}">
                  <span>{{ row.fromUnit }}</span>
                </template>
              </el-table-column>
              <el-table-column min-width="180" header-align="center" label="转换后单位">
                <template slot-scope="{row}">
                  <span>{{ row.toUnit }}</span>
                </template>
              </el-table-column>
              <el-table-column min-width="210" header-align="center" label="转换关系">
                <template slot-scope="{row}">
                  <span v-if="row.edit">
                    <span v-if="row._edit">
                      1 {{ row.fromUnit }} * 
                      <el-input v-model="row.cf" style="width:100px;margin-right:10px;" />
                      =1 {{ row.toUnit }}
                      <i class="el-icon-check" style="cursor:pointer;color:green;font-size:15px;"  @click="saveCf(row)" />
                    </span>
                    <span v-else>
                      1 {{ row.fromUnit }} * {{ row.cf }} = 1 {{ row.toUnit }}
                      <i class="el-icon-edit" style="cursor:pointer;color:blue;font-size:15px;" @click="row._edit=true" />
                    </span>
                  </span>
                  <span v-else>
                    1 {{ row.fromUnit }} * {{ row.cf }} = 1 {{ row.toUnit }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="营养素含量计算" name="calc">
            <div>
              <el-input v-model="calc.req.amt" placeholder="摄入量" style="width:100px;margin-right:10px;" />
              <DataSelect
                url="/api/units"
                placeholder="摄入量单位"
                :value.sync="calc.req.unitId"
                :label.sync="calc.req.unitName"
                :initOptions="dlg.form.modifierUnitOptions"
                width="110px"
              />
              <el-button :loading="calc.loading" size="mini" type="success" style="margin-left:15px;" @click="calcNvIn">计算</el-button>
              <span>
                {{ calc.rsp.amt }}{{ calc.rsp.unitName }}
              </span>
            </div>
            <div style="margin-top:5px;">
              <p v-for="nv in calc.rsp.nvList" :key="nv.name">{{ nv.name }} 摄入：{{ nv.nvIn }}{{ nv.nvUnit }}, ({{ nv.nv }}{{ nv.nvUnit }}/{{ nv.nvSpec }}{{ nv.nvSpecUnit }})</p>
            </div>

            <div style="margin-top:5px;">
              <el-input v-model="cf.req.fromAmt" placeholder="源单位数量" style="width:100px;margin-right:10px;" />
              <DataSelect
                url="/api/units"
                placeholder="源单位"
                :value.sync="cf.req.fromUnitId"
                :label.sync="cf.req.fromUnit"
                :initOptions="dlg.form.modifierUnitOptions"
                width="110px"
              />
              -
              <DataSelect
                url="/api/units"
                placeholder="目标单位"
                :value.sync="cf.req.toUnitId"
                :label.sync="cf.req.toUnit"
                :initOptions="dlg.form.modifierUnitOptions"
                width="110px"
              />
              <el-button :loading="cf.loading" size="mini" type="success" style="margin-left:15px;" @click="calcCf">计算转换</el-button>
            </div>

            <div>
              <span v-if="!!cf.rsp.error">
                {{ cf.rsp.error }}
              </span>
              <span v-else-if="cf.rsp.steps.length>0">
                <div style="margin-bottom:5px;">
                  {{ cf.rsp.fromAmt }}{{ cf.rsp.fromUnit }} * {{ cf.rsp.cf }} =  {{ cf.rsp.toAmt }}{{ cf.rsp.toUnit }}
                </div>
                <div v-for="step in cf.rsp.steps" :key="step.convert.fromUnit" style="margin-bottom:5px;">
                  【1{{ step.convert.fromUnit }} * {{ step.convert.cf }} = 1{{ step.convert.toUnit }}，{{ step.cf }}】
                  {{ step.fromAmt }}{{ step.convert.fromUnit }} * {{ step.convert.cf }} = {{ step.toAmt }}{{ step.convert.toUnit }}
                </div>
              </span>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dlg.form.visible = false">
          取消
        </el-button>
        <el-button :loading="dlg.form.saveLoading" size="mini" type="primary" @click="onlySave">
          仅保存
        </el-button>
        <el-button :loading="dlg.form.saveLoading" size="mini" type="primary" @click="M.save()">
          保存并退出
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { fGet, fPost, fSave } from '@/api/rest'
import { M } from '@/api/op'
import DataSelect from '@/views/components/DataSelect/index'
import fn from '@/api/fn'

export default {
  components: { Pagination, DataSelect },
  data() {
    return {
      M: new M(this),
      fn,
      URI: '/api/foods',
      maxHeight: 600,
      baseUnitOptions: [],
      tempList: [{
        _edit: true
      },{}],
      list: {
        main: {
          loading: true,
          total: 0,
          list: [],
          render(row) {
            row.modifiers = row.modifiers || []
            row.nutrients = row.nutrients || []
            row.modifiers && row.modifiers.forEach(v => v._edit = true)
            row.nutrients && row.nutrients.forEach(v => {
              v._edit = true
              v._nutrientUnitOptions = []
            })
            row.cfs = row.cfs || []
            row.cfs && row.cfs.forEach(v => {
              v._edit = false
            })
            return row
          },
          query: {
            page: 1,
            limit: 50
          }
        }
      },
      calc: {
        loading: false,
        req: {
          amt: undefined,
          unitId: undefined,
          unitName: undefined
        },
        rsp: {
          amt: undefined,
          unitName: undefined,
          nvList: []
        }
      },
      cf: {
        loading: false,
        req: {
          fromAmt: undefined,
          fromUnitId: undefined,
          fromUnit: undefined,
          toUnitId: undefined,
          toUnit: undefined
        },
        rsp: {
          steps: []
        }
      },
      dlg: {
        form: {
          infoTab: 'base',
          visible: false,
          title: '',
          data: {
            modifiers: [],
            nutrients: []
          },
          saveLoading: false,
          modifierUnitOptions: [],
          rules: {
            // type: [{ required: true, message: '请选择主/辅料', trigger: 'blur' }],
            name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
          }
        }
      }
    }
  },
  created() {
    this.maxHeight = document.documentElement.clientHeight - 135
    this.M.list()
  },
  methods: {
    // 加载详细信息
    loadDetail(id) {
      fGet(`${this.URI}/${id}`).then(res => {
        const detail = {
          ...res
        }
        detail.modifiers && detail.modifiers.forEach(v => v._edit = true)
        detail.nutrients && detail.nutrients.forEach(v => {
          v._edit = true
          v._nutrientUnitOptions = []
        })
        detail.cfs && detail.cfs.forEach(v => {
          v._edit = false
        })
        this.dlg.form.data = detail
        this.modifierUnitChange()
      })
    },
    // 新增
    create() {
      this.dlg.form.modifierUnitOptions = []
      this.M.create({ form: 'form', title: '新增', data: {} })
    },
    // 编辑
    edit(row) {
      this.dlg.form.modifierUnitOptions = []
      this.M.edit({ form: 'form', title: 'name', row: row })
      this.loadDetail(row.id)
    },
    // 自定义单位判断
    isCustomUnit(id, name) {
      return !!name && name.trim().length > 0 && (!id || id == 'CUSTOM_UNIT' || id.length == 0 || id == name)
    },
    // 规格单位列表生成
    modifierUnitChange() {
      const modifierUnitOptions = []
      const modifierUnitInclude = {}
      this.dlg.form.data.modifiers.forEach(modifier => {
        const unitId = modifier.unitId || ''
        const unitName = modifier.unitName || ''
        if (this.isCustomUnit(unitId, unitName)) {
          const name = modifier.name || ''
          if (!!(modifier.unitName) && modifier.unitName.trim().length > 0) {
            modifier.key = (unitName == name ? unitName : `${unitName}${name}`)
            modifierUnitOptions.push({
              label: modifier.key,
              value: modifier.key
            })
            modifierUnitInclude[modifier.key] = true
          }
        } else {
          modifier.key = unitName
        }        
      })
      this.dlg.form.data.modifiers.forEach(modifier => {
        if (!!(modifier.toModifierName) && !modifierUnitInclude[modifier.toModifierName]) {
          modifier.toModifierId = undefined
          modifier.toModifierName = undefined
        }
      })
      this.dlg.form.modifierUnitOptions = modifierUnitOptions
    },
    // 添加规格
    addModifier(row) {
      row.modifiers.push({
      _edit: true,
      })
    },
    // 删除规格
    removeModifier(row, index) {
      row.modifiers.splice(index, 1)
    },
    // 添加营养素
    addNutrient(row) {
      row.nutrients.push({
        _edit: true,
        _nutrientUnitOptions: []
      })
    },
    // 删除营养素
    removeNutrient(row, index) {
      row.nutrients.splice(index, 1)
    },
    // 导入营养素模版
    importNutrientTemplate() {
      console.log(this.dlg.form.data.nutrients)
      if (this.dlg.form.selectedNutrientTemplate == undefined) {
        return
      }

      if (this.dlg.form.data.nutrients == undefined) {
        this.dlg.form.data.nutrients = []
      }

      this.dlg.form.nutrientTemplateOptions.forEach(opt => {
        if (opt.name == this.dlg.form.selectedNutrientTemplate) {
          this.dlg.form.selectedNutrientTemplateId = opt.id
        }
      })

      fGet(`/api/nutrient-templates/${this.dlg.form.selectedNutrientTemplateId}/nutrients`, {}).then(res => {
        if (res == undefined) {return}
        
        let existed = false
        // 渲染营养素
        res.forEach(nv => {
          // 筛选营养素
          this.dlg.form.data.nutrients.forEach(existNv => {
            if (nv.nutrientId == existNv.nutrientId) {
              existed = true
            }
          })

          if (! existed) {
            this.dlg.form.data.nutrients.push({
              _edit: true,
              _nutrientUnitOptions: [],
              nutrientId: nv.nutrientId, 
              nutrientName: nv.nutrientName, 
              nvUnit: nv.unit, 
              nvSpec: nv.nvSpec, 
              nvSpecUnit: nv.nvSpecUnit,
              nvSpecUnitId: nv.nvSpecUnitId,
              nvUnitId: nv.unitId,
              nvMeasureMode: nv.quantityType
            })
          }

        })
      })

    },
    getNutrienttemplateList(e, row) {
      row.nutrientTemplateOptions = []
      fGet(`/api/nutrient-templates`, {keyword: e.target.value}).then(res => {
        this.$set(row, 'nutrientTemplateOptions', res)
        console.log(row.nutrientTemplateOptions)
      })
    },
    // 营养素选择
    nutrientSelect(nutrient, row) {
      row._nutrientUnitOptions = []
      if (nutrient._data && nutrient._data.unitName) {
        row._nutrientUnitOptions.push({
          value: nutrient._data.unitId == 'CUSTOM_UNIT' ? nutrient._data.unitName : nutrient._data.unitId,
          label: nutrient._data.unitName
        })
      }
      if (nutrient._data && nutrient._data.optionUnits) {
        nutrient._data.optionUnits.forEach(optionUnit => {
          row._nutrientUnitOptions.push({
            value: optionUnit.unitId == 'CUSTOM_UNIT' ? optionUnit.name : optionUnit.unitId,
            label: optionUnit.name
          })
        })
      }
    },
    // 食物信息标签切换
    foodInfoTabClick(tab) {
    },
    // 计算营养素摄入量
    calcNvIn() {
      this.calc.loading = true
      fPost(`/api/foods/${this.dlg.form.data.id}`, this.calc.req).then(res => {
        this.calc.rsp = res
      }).finally(() => {
        this.calc.loading = false
      })
    },
    // 计算单位转换
    calcCf() {
      this.cf.loading = true
      fPost(`/api/foods/${this.dlg.form.data.id}/unit-cf`, this.cf.req).then(res => {
        this.cf.rsp = res
      }).finally(() => {
        this.cf.loading = false
      })
    },
    // 刷新 CF
    refreshCf() {
      fGet(`/api/foods/${this.dlg.form.data.id}/cfs`).then(res => {
        this.dlg.form.data.cfs = res.map(v => {
          v._edit = false
          return v
        })
      })
    },
    // 保存 CF
    saveCf(cf) {
      fPost(`/api/foods/${this.dlg.form.data.id}/cfs`, cf).then(res => {
        this.refreshCf()
      })
      cf._edit = false
    },
    // 仅保存
    onlySave() {
      this.dlg.form.saveLoading = true
      fSave(this.URI, this.dlg.form.data).then(res => {
        this.$message.success('保存成功')
        this.refreshCf()
      }).finally(() => {
        this.dlg.form.saveLoading = false
      })
    }
  }
}
</script>
