数据转换很烦的页面

<template>
  <el-card shadow="never" class="mb-2" v-loading="cardLoading">
    <div>
      <el-divider content-position="left">用量录入</el-divider>
      <el-form :model="formData" label-width="auto" style="max-width: 600px">
        <el-form-item label="用餐客户">
          <el-select @change="selectOrgId"  v-model="formData.clientOrgId" placeholder="请选择客户">
            <el-option
              v-for="item in customerData"
              :key="item.id"
              :label="item.orgName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        
        <!-- https://blog.csdn.net/qq_45104829/article/details/139085998 -->
        <el-form-item label="用餐人数">
          <el-input
            v-model="formData.diners"
            type="number"
            oninput="value=value.replace(/[^\d.]/g,'')"
          />
        </el-form-item>

        <el-form-item label="用餐时间">
          <el-date-picker
          
           @change="changeTime"
            style="width: 100%"
            v-model="formData.measurementDate"
            type="date"
            placeholder="请选择时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
    </div>

    <el-divider content-position="left">用餐录入</el-divider>

    <div class="table-box">
      <el-form :inline="true" :model="formInline" class="meal-table-inline">
        <el-form-item label="餐次">
          <el-select style="width:140px" v-model="whichMealID" placeholder="请选择餐次">
            <el-option
              v-for="item in mealTimesData"
              :key="item.id"
              :label="item.scheduleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="食材名称">
         
          <el-select
            v-model="formInline.foodObj"
            value-key="id"
            filterable
            allow-create
            remote
            reserve-keyword
            placeholder="请输入搜索食材"
            :remote-method="searchForIngredients"
            :loading="otherForm.loading"
            remote-show-suffix
            style="width: 240px"
          >
            <el-option
              v-for="item in foodAllData"
              :key="item.id"
              :label="item.ingredientName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用量">
          <el-input
            style="width: 260px"
            oninput="value=value.replace(/[^\d.]/g,'')"
            v-model="formInline.useNum"
            placeholder="请输入用量"
          >
            <template #append>
              <el-select
                value-key="unitValue"
                v-model="unitObj"
                placeholder="选择单位"
                style="width: 115px"
              >
                <el-option
                  v-for="(item, index) in unitList"
                  :key="index"
                  :label="item.unitName"
                  :value="item"
                />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">新增</el-button>
        </el-form-item>
      </el-form>
      <!-- ttttttttttt -->
      <el-table :data="tableData" border :span-method="objectSpanMethod" >
        <el-table-column
          
          align="center"
          prop="whichMealName"
          label="餐次"
          min-width="110"
        />
        <el-table-column
          align="center"
          prop="ingredientName"
          label="食品名称"
          min-width="150"
        />

        <el-table-column label="用量">
          <template v-slot="scope">
            <span>{{ scope.row.inputValue }}</span>
            <span>{{ scope.row.inputUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="营养成分" >
          <el-table-column
          min-width="110"
            v-for="(item, index) in standardNutritionDictionary"
            :key="index"
            :label="item.nutrientName"
          >
            <template v-slot="scope">
              <span>
                {{ scope.row.NutrientList[index].contentValue
                }}{{ scope.row.NutrientList[index].unit }}</span
              >
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column align="center" fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button type="danger" @click="delItem(scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      
    </div>
    <div class="end-button">



      <el-button size="large" @click="ClearClose">取消</el-button>
        <el-button
          size="large"
          type="primary"
          :loading="submitLoading"
          @click="addNewSubmiss"
          >提 交</el-button
        >
      </div>
  </el-card>
</template>

<script setup lang="ts">
import Decimal from "decimal.js";
Decimal.set({ precision: 3 });
import { ref, computed, onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import API_FOODDICTIONARY from "@/api/foodDictionaryApi";
import API_NUTRIENT from "@/api/nutrientApi";
import API_FOOD from "@/api/foodApi";
import API_MEAL from "@/api/mealApi";
import { totalCustomer } from "@/hooks/selectCustomer";
const { requestAllCustomer } = totalCustomer();


const route = useRoute();
const router = useRouter();
const standardNutritionDictionary = ref([]);
const cardLoading = ref(false);
const submitLoading = ref(false);
const customerData = ref([]);
const mealTimesData = ref([]);
const foodAllData = ref([]);
const tableData = ref([]);
const whichMealID = ref("")
const formInline = ref({
  foodObj: "",
  useNum: "",
  useUnit: ""
});
const otherForm = reactive({
  other: "",
  loading: false,
  options: []
});

const unitList = ref([
  { unitName: "千克", unitValue: 1000 },
  { unitName: "克", unitValue: 1 },
  { unitName: "公斤", unitValue: '1000' },
  { unitName: "斤", unitValue: 500 }
]);
const unitObj = ref({
  unitName:'斤',
  unitValue: 500 

});
const formData = ref({
  clientOrgId: "",
  diners: "",
  measurementDate: ""
});

const onChildClick= async (val) => {

  getMealDictionary();
  GetNutritionDictionary(val);
  let resList = await requestAllCustomer();
  customerData.value = resList.resultData;
    // console.log('父组件调用了子组件')
};


onMounted(async () => {
  // getMealDictionary();
  // GetNutritionDictionary();
  // let resList = await requestAllCustomer();
  // customerData.value = resList.resultData;
});


const selectOrgId =(itemID)=>{
  let resData = customerData.value.find(item => item.id === itemID);
  formData.value.diners = resData.peopleCount
  // return
  // API_MEAL.mealPersons(itemID)
  //   .then(resData => {
  //     formData.value.diners = resData.data
  //   })
  //   .finally(() => {});
};



const handleTableData = (tableData: any) => {
  let rowSpanArr: any = [],
    position = 0;
  tableData.forEach((item: any, index: number) => {
    if (index == 0) {
      rowSpanArr.push(1);
      position = 0;
    } else {
      if (item.whichMealName == tableData[index - 1].whichMealName) {
        rowSpanArr[position] += 1; //id相同,数组中的某一项值+1
        rowSpanArr.push(0);   // 被合并的行,push 0 占位
      } else {
        rowSpanArr.push(1);
        position = index;
      }
    }
  });
  return rowSpanArr;
};

const objectSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  let rowSpanArr = handleTableData(tableData.value);
  if (columnIndex === 0) {
    const rowSpan = rowSpanArr[rowIndex];
    return {
      rowspan: rowSpan, //行
      colspan: 1, //列
    };
  }
};



const searchForIngredients = val => {
  if (val === "") {
    return;
  }
  const postData = {
    pageSize: 9999,
    pageNum: 1,
    ingredientName: val
  };
  otherForm.loading = true;
  API_FOOD.foodPageList(postData)
    .then(resData => {
      foodAllData.value = resData.data.list;
    })
    .finally(() => {
      otherForm.loading = false;
    });
};

const getGoodsDetail = (val) => {
  formInline.value.foodObj ="";
  formInline.value.useNum ="";
  formInline.value.useUnit ="";


  if (val === null) {
    tableData.value=[]
    formData.value.clientOrgId ="";
    formData.value.diners ="";
    formData.value.measurementDate ="";
    return;
  }
  // 这是编辑的时候的详情
  API_MEAL.detailMeal(val)
    .then(resData => {
      formData.value = resData.data;
      let newMealGoods = resData.data.consumptionItems.map(item => {
        let floorData = combineNewArrayNutrient(
          item.computed.contentValues,
          standardNutritionDictionary.value
        );
        return {
          ...item,
          whichMealName:getMealName(item.mealScheduleId),
          NutrientList: floorData
        };
      });
      sortFun(newMealGoods)
      
    })
    .finally(() => {});
};

const sortFun=(sortList)=>{
  sortList.sort((a, b) => {
    return a.whichMealName > b.whichMealName ? 1 : -1
  })
  tableData.value = sortList;
  // console.log(sortList)
   
}
const getMealName=(mealScheduleId)=>{

    const itemObj = mealTimesData.value.find(item => item.id === mealScheduleId);
    // console.log(itemObj)
    return itemObj.scheduleName
}
const GetNutritionDictionary = (val) => {
  API_NUTRIENT.list()
    .then(data => {
      standardNutritionDictionary.value = data.data;
      getGoodsDetail(val);
    })
    .finally(() => {});
};

const getMealDictionary = () => {
  API_FOODDICTIONARY.listDictionary()
    .then(data => {
      mealTimesData.value = data.data;
    })
    .finally(() => {});
};

const getUsefulEatNum = (dosage, UnitNum, eatPart) => {
  let newNum = new Decimal(dosage)
    .mul(new Decimal(UnitNum))
    .mul(new Decimal(eatPart / 100));
  return newNum.toString();
};

// 这是新增不是提交
const onSubmit = () => {
  if (whichMealID.value === "") {
    ElMessage.error("请选择餐次");
    return;
  }
  if (formInline.value.foodObj === "") {
    ElMessage.error("请输入食材名称");
    return;
  }
  if (formInline.value.useNum === "") {
    ElMessage.error("请输入用量");
    return;
  }
  if (unitObj.value === "") {
    ElMessage.error("请输入单位");
    return;
  }
  let edibleEatNum = getUsefulEatNum(
    formInline.value.useNum,
    unitObj.value.unitValue,
    formInline.value.foodObj.ediblePortion
  );
  const postData = {
    id: formInline.value.foodObj.id,
    consumptionValue: edibleEatNum
  };
  API_MEAL.computeMeal(postData)
    .then(data => {
      const resuFind = containsId(tableData.value, data.data.ingredientName,whichMealID.value)
      if(resuFind){
        ElMessage.error('食品列表已经包含'+data.data.ingredientName+",不可重复添加")
        return
      }
      tableData.value.push({
        ingredientName: formInline.value.foodObj.ingredientName,
        NutrientList: combineNewArrayNutrient(
          data.data.computed.contentValues,
          standardNutritionDictionary.value
        ),
        consumptionValue: edibleEatNum,
        ingredientId: formInline.value.foodObj.id,
        inputValue: formInline.value.useNum,
        inputUnit: unitObj.value.unitName,
        sortNum: tableData.value.length === 0 ? 0 : tableData.value.length,
        mealScheduleId:whichMealID.value,
        whichMealName:getMealName(whichMealID.value),
        
      });
      sortFun(tableData.value)
    })
    .finally(() => {});
};

function containsId(array, nameFind,  MealIDFind) {
  return array.some(item => item.ingredientName === nameFind && item.mealScheduleId === MealIDFind);
}
function combineNewArrayNutrient(smallList, longList) {
  longList.forEach((obj2, index) => {
    const found = smallList.some(
      obj1 => obj1.nutrientName === obj2.nutrientName
    );
    if (!found) {
      smallList.splice(index, 0, {
        ...obj2,
        contentValue: "0"
      });
    }
  });
  return smallList;
}
const delItem = indexNum => {
  ElMessageBox.confirm("确定删除此条数据吗?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      tableData.value.splice(indexNum, 1);
      ElMessage({
        type: "success",
        message: "成功删除"
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};
const changeTable = listData => {
  let newData = listData.map(item => {
    return {
      ingredientId: item.ingredientId,
      consumptionValue: item.consumptionValue,
      inputValue: item.inputValue,
      inputUnit: item.inputUnit,
      sortNum: item.sortNum,
      mealScheduleId:item.mealScheduleId
      
    };
  });

  return newData;
};


const emits = defineEmits(["FatherClick"]);
const ClearClose =()=>{
  emits("FatherClick");
}

const changeTime =()=>{
    console.log(formData.value.measurementDate)
    let postData={
      date:formData.value.measurementDate,
      clientOrgId:formData.value.clientOrgId,
    }

     API_MEAL.mealInputByDate(postData)
    .then(resData => {
      console.log(resData.data.consumptionItems)
      const DailyIngredients = resData.data.consumptionItems
      let newMealGoods = resData.data.consumptionItems.map(item => {
        let floorData = combineNewArrayNutrient(
          item.computed.contentValues,
          standardNutritionDictionary.value
        );
        return {
          ...item,
          whichMealName:getMealName(item.mealScheduleId),
          NutrientList: floorData
        };
      });
      sortFun(newMealGoods)
    })
    .finally(() => {});


}

// 这是提交数据
const addNewSubmiss = () => {
  console.log(tableData.value)
  console.log(changeTable(tableData.value));
  return
  if(formData.value.id){
    ElMessageBox.confirm("确定提交此次编辑的数据吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      SubmitData()
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
  }else{
    SubmitData()
  }
};


const SubmitData =()=>{
  console.log(formData.value);
  console.log(changeTable(tableData.value));
  if (tableData.value.length === 0) {
    ElMessage.error("请添加食材");
    return;
  }

  const postData = {
    ...formData.value,
    consumptionItems: changeTable(tableData.value)
  };
  // console.log(postData)
  // return
  submitLoading.value = true;
  let promiseResule = formData.value.id ? API_MEAL.updateMeal(postData) : API_MEAL.addMeal(postData);
  promiseResule
    .then(value => {
      console.log(value);
      ElMessage({
        message: "编辑成功",
        type: "success",
        plain: true
      });

      setTimeout(() => {
        ClearClose();
      }, 500);
    })
    .finally(() => {
      submitLoading.value = false;
    });
}
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "mealUpdate"
});


defineExpose({ onChildClick }); 
</script>



<style scoped>



.end-button {
  margin: 40px 0px  0px 0px;
  display: flex;
  justify-content: center;
}
.table-box {
  box-sizing: border-box;
  padding: 10px;
  /* border: 1px solid #dcdfe6; */
}
.meal-table-inline {
  border-top: 1px solid #dcdfe6;
  border-left: 1px solid #dcdfe6;
  border-right: 1px solid #dcdfe6;
  /* background: sandybrown; */
  box-sizing: border-box;
  padding-left: 10px;
}
.meal-table-inline .el-form-item {
  margin-top: 18px;
}
</style>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容