<template>
  <el-card shadow="always">
    <el-button type="primary" plain  size="large" @click="close()">返回</el-button>
    <span style="margin-left: 20px;">{{isView?'查看食材':form.foodIngredientId?'编辑食材':'食材管理'}}</span>
  </el-card>
  <div class="p-2">
    <el-menu class="el-menu-demo" mode="horizontal" @select="handleSelect" :default-active="currentIndex">
      <el-menu-item index="1">基本信息</el-menu-item>
      <el-menu-item index="2">营养元素</el-menu-item>
    </el-menu>

    <el-card shadow="always" v-show="baseInfoIndex==currentIndex">
      <div  width="1024px"  :style=divStyle>
        <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="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="食材分类" prop="foodCategoryId">                
                  <el-cascader :disabled="isView"
                  v-model="form.foodCategoryIds"
                  :options="foodCategoryList"
                  :props="{value:'foodCategoryId',label:'name'}"  style="width: 100%"                   
                />
              </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6">
              <el-form-item label="食材名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" :disabled="isView" />
              </el-form-item>
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row>

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="食材编码" prop="code">
            <el-input v-model="form.code" placeholder="系统生成"  :disabled="true"/>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6">
              <el-form-item label="单位" prop="unit">             
            <el-select v-model="form.unit" placeholder="请选择"   clearable :disabled="isView">
                <el-option v-for="dict in food_unit" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
          </el-form-item>
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row>

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="入货价格" prop="purchasePrice">
            <el-input v-model="form.purchasePrice" placeholder="请输入" :disabled="isView">
              <template #append><span>元</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6">
              <el-form-item label="食材可食比例构成" prop="edibleRatio">
            <el-input v-model="form.edibleRatio" placeholder="请输入" :disabled="isView" >
              <template #append><span>%</span></template>
          </el-input>
          </el-form-item>
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row>

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="保质期" prop="shelfLife">
            <el-input v-model="form.shelfLife" placeholder="请输入" :disabled="isView">
              <template #append><span>天</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6">
              <el-form-item label="库存预警值" prop="stockWarning">
            <el-input v-model="form.stockWarning" placeholder="请输入" :disabled="isView">
              <template #append><span>g</span></template>
          </el-input>
          </el-form-item>
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row>

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="保质期预警" prop="expiryWarning">
            <el-input v-model="form.expiryWarning" placeholder="请输入" :disabled="isView">
              <template #append><span>天</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6">               
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row>

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="15">
              <el-form-item label="食材描述" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" :rows="10" maxlength="200" show-word-limit :disabled="isView"/>
          </el-form-item>
            </el-col>            
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row>
        </el-form>
      </div>
    </el-card>


    <el-card shadow="always" v-show="nutrientIndex==currentIndex">
      <div  width="1024px"  :style=divStyle>        
        <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 style="margin-bottom: 20px;">            
            <el-col :span="24" style="margin-left: 100px;">  
              <div><span style="color: red;font-size: 15px;">注：每100（g/ml） 含量</span></div>                         
            </el-col>                   
          </el-row>
          
          
          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="热量" prop="calories">
            <el-input v-model="form.calories" placeholder="请输入" :disabled="isView">
              <template #append><span>kcal</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6"> 
              <el-form-item label="蛋白质" prop="protein">
            <el-input v-model="form.protein" placeholder="请输入" :disabled="isView">
              <template #append><span>g</span></template>
          </el-input>
          </el-form-item>              
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row> 

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="脂肪" prop="fat">
            <el-input v-model="form.fat" placeholder="请输入" :disabled="isView">
              <template #append><span>g</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6"> 
              <el-form-item label="碳水化合物" prop="carbohydrate">
            <el-input v-model="form.carbohydrate" placeholder="请输入" :disabled="isView">
              <template #append><span>g</span></template>
          </el-input>
          </el-form-item>         
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row>          

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="水分" prop="water">
            <el-input v-model="form.water" placeholder="请输入" :disabled="isView">
              <template #append><span>ml</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6"> 
              <el-form-item label="维生素A" prop="vitaminA">
            <el-input v-model="form.vitaminA" placeholder="请输入" :disabled="isView">
              <template #append><span>μg</span></template>
          </el-input>
          </el-form-item> 
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row> 
          
          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="维生素B2" prop="vitaminB2">
            <el-input v-model="form.vitaminB2" placeholder="请输入" :disabled="isView">
              <template #append><span>mg</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6"> 
              <el-form-item label="维生素C" prop="vitaminC">
            <el-input v-model="form.vitaminC" placeholder="请输入" :disabled="isView">
              <template #append><span>mg</span></template>
          </el-input>
          </el-form-item>
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row> 

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="钠" prop="sodium">
            <el-input v-model="form.sodium" placeholder="请输入" :disabled="isView">
              <template #append><span>mg</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6"> 
              <el-form-item label="铁" prop="iron">
            <el-input v-model="form.iron" placeholder="请输入" :disabled="isView">
              <template #append><span>mg</span></template>
          </el-input>
          </el-form-item>
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row> 

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="磷" prop="phosphorus">
            <el-input v-model="form.phosphorus" placeholder="请输入" :disabled="isView">
              <template #append><span>mg</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6"> 
              <el-form-item label="膳食纤维" prop="dietaryFiber">
            <el-input v-model="form.dietaryFiber" placeholder="请输入" :disabled="isView">
              <template #append><span>g</span></template>
          </el-input>
          </el-form-item>
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row> 

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="维生素B1" prop="vitaminB1">
            <el-input v-model="form.vitaminB1" placeholder="请输入" :disabled="isView">
              <template #append><span>mg</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6"> 
              <el-form-item label="烟酸" prop="niacin">
            <el-input v-model="form.niacin" placeholder="请输入" :disabled="isView">
              <template #append><span>mg</span></template>
          </el-input>
          </el-form-item>
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row> 

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="维生素E" prop="vitaminE">
            <el-input v-model="form.vitaminE" placeholder="请输入" :disabled="isView">
              <template #append><span>mg</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6"> 
              <el-form-item label="钙" prop="calcium">
            <el-input v-model="form.calcium" placeholder="请输入" :disabled="isView">
              <template #append><span>mg</span></template>
          </el-input>
          </el-form-item>
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row> 

          <el-row>            
            <el-col :span="3" style="margin-left: -100px;">              
            </el-col>
            <el-col :span="6">
              <el-form-item label="钾" prop="potassium">
            <el-input v-model="form.potassium" placeholder="请输入" :disabled="isView">
              <template #append><span>mg</span></template>
          </el-input>
          </el-form-item>
            </el-col> 
            <el-col :span="3">               
            </el-col>  
            <el-col :span="6"> 
              <el-form-item label="胆固醇" prop="cholesterol">
            <el-input v-model="form.cholesterol" placeholder="请输入" :disabled="isView">
              <template #append><span>g</span></template>
          </el-input>
          </el-form-item>
            </el-col>  
            <el-col :span="3">               
            </el-col> 
            <el-col :span="3">               
            </el-col>  
          </el-row> 
        </el-form>
      </div>
    </el-card>

    <el-card shadow="always" class="card-footer" v-if="!isView">
    <div>
        <el-button type="primary" size="large" plain @click="close" v-hasPermi="['system:hospital:add']">
          &nbsp;&nbsp;&nbsp;取消&nbsp;&nbsp;&nbsp;
        </el-button>
        <el-button type="primary" size="large" @click="submitForm" v-hasPermi="['system:hospital:add']">
          &nbsp;&nbsp;&nbsp;保存&nbsp;&nbsp;&nbsp;
        </el-button>
      </div>
  </el-card>
  </div>
</template>

<script setup name="FoodIngredient" lang="ts">
import { listFoodIngredient, getFoodIngredient, delFoodIngredient, addFoodIngredient, updateFoodIngredient } from '@/api/system/foodIngredient';
import { FoodIngredientVO, FoodIngredientQuery, FoodIngredientForm } from '@/api/system/foodIngredient/types';
import { listTree} from '@/api/system/foodCategory';
import { FoodCategoryVO} from '@/api/system/foodCategory/types';
import { object } from 'vue-types';
import { fa } from 'element-plus/es/locale/index.mjs';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {  food_unit } = toRefs<any>(proxy?.useDict('food_unit'));

const foodIngredientList = ref<FoodIngredientVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

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

const queryFormRef = ref<ElFormInstance>();
const foodIngredientFormRef = ref<ElFormInstance>();
const baseInfoIndex = ref('1')
const nutrientIndex  = ref('2')
const currentIndex  = ref('1')
const isView  = ref<boolean>(false)
const foodCategoryList = ref<FoodCategoryVO[]>([]);
const route = useRoute();

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

const initFormData: FoodIngredientForm = {
  foodIngredientId: undefined,
  foodCategoryId: undefined,
  foodCategoryIds: undefined,
  name: undefined,
  code: undefined,
  unit: undefined,
  purchasePrice: undefined,
  edibleRatio: 100,
  shelfLife: undefined,
  stockWarning: undefined,
  expiryWarning: undefined,
  description: undefined,
  calories: undefined,
  protein: undefined,
  fat: undefined,
  carbohydrate: undefined,
  water: undefined,
  vitaminA: undefined,
  vitaminB2: undefined,
  vitaminC: undefined,
  sodium: undefined,
  iron: undefined,
  phosphorus: undefined,
  dietaryFiber: undefined,
  vitaminB1: undefined,
  niacin: undefined,
  vitaminE: undefined,
  calcium: undefined,
  potassium: undefined,
  cholesterol: undefined,
  status: undefined,
}
const data = reactive<PageData<FoodIngredientForm, FoodIngredientQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    foodCategoryId: undefined,
    name: undefined,
    code: undefined,
    unit: undefined,
    purchasePrice: undefined,
    edibleRatio: undefined,
    shelfLife: undefined,
    stockWarning: undefined,
    expiryWarning: undefined,
    description: undefined,
    calories: undefined,
    protein: undefined,
    fat: undefined,
    carbohydrate: undefined,
    water: undefined,
    vitaminA: undefined,
    vitaminB2: undefined,
    vitaminC: undefined,
    sodium: undefined,
    iron: undefined,
    phosphorus: undefined,
    dietaryFiber: undefined,
    vitaminB1: undefined,
    niacin: undefined,
    vitaminE: undefined,
    calcium: undefined,
    potassium: undefined,
    cholesterol: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {    
    foodCategoryId: [
      { required: true, message: "食材分类ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "食材名称不能为空", trigger: "blur" }
    ],    
    unit: [
      { required: true, message: "单位不能为空", trigger: "blur" }
    ],
  }
});

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


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

const getListTree = async () => {   
  const res = await listTree(queryParams.value);  
  foodCategoryList.value = res.rows;   
}

/** 查询食材管理列表 */
const getList = async () => {
  const foodIngredientId = route.params && route.params.id;
  const vfoodIngredientId = route.params && route.params.vid;
  let id=undefined;
  if(vfoodIngredientId){
    isView.value=true;
    id=vfoodIngredientId;
  }else{
    isView.value=false ;
    id=foodIngredientId;
  }
  
  if (id&&id!='0') {
    loading.value = true;
    const res = await getFoodIngredient(id as string);
    Object.assign(form.value, res.data);
    form.value.foodCategoryIds=res.data.foodCategoryId.toString().split(',') ;
    loading.value = false;
  }  
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  foodIngredientFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: FoodIngredientVO[]) => {
  ids.value = selection.map(item => item.foodIngredientId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加食材管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: FoodIngredientVO) => {
  reset();
  const _foodIngredientId = row?.foodIngredientId || ids.value[0]
  const res = await getFoodIngredient(_foodIngredientId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改食材管理";
}

/** 提交按钮 */
const submitForm = () => {
  foodIngredientFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      let params=ref<FoodIngredientForm>({});
      Object.assign(params.value, form.value);
      params.value.foodCategoryId = form.value.foodCategoryIds.join(',')
      if (form.value.foodIngredientId) {
        await updateFoodIngredient(params.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addFoodIngredient(params.value).then(res=>{
          form.value.foodIngredientId=res.data;
        }).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功"); 
      if(currentIndex.value=='2'){
        close()
      }else{
        currentIndex.value='2';   
      }           
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: FoodIngredientVO) => {
  const _foodIngredientIds = row?.foodIngredientId || ids.value;
  await proxy?.$modal.confirm('是否确认删除食材管理编号为"' + _foodIngredientIds + '"的数据项？').finally(() => loading.value = false);
  await delFoodIngredient(_foodIngredientIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/foodIngredient/export', {
    ...queryParams.value
  }, `foodIngredient_${new Date().getTime()}.xlsx`)
}


const handleSelect = (key: string, keyPath: string[]) => {
  currentIndex.value=key.toString()   
  // console.log(key, keyPath,currentIndex)
}

onMounted(() => {
  getListTree()
  getList();
  let timerId=setInterval(() => {   
    if(food_unit&&food_unit.value.length>0){
      form.value.unit=food_unit.value[0].value;      
      clearInterval(timerId);
    }    
  }, 300);
  
});
</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;     
}
</style>
