<template>
  <el-dialog
    :title="title + ' - 原料'"
    :visible.sync="visible"
    width="1330px"
    append-to-body
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="handleClose"
  > 
    <div style="width: 100%;height: 600px;overflow-y: auto;">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基础信息" name="basic">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="原料编号" prop="materialCode">
                  <el-input
                    v-model="form.materialCode"
                    placeholder="请输入原料编号"
                    maxlength="40"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="原料名称" prop="materialName">
                  <el-input
                    v-model="form.materialName"
                    placeholder="请输入原料名称"
                    maxlength="40"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="原料类别" prop="materialTypeId">
                  <el-cascader v-model="form.materialTypeId"
                    :options="treeTypeOptions" :filterable="true" style="width: 100%;" :show-all-levels="false"
                    :props="{ 
                      emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                      checkStrictly: true,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                      value:'id',label:'categoryName'
                    }" clearable >
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属区域" prop="areaId">
                  <el-cascader v-model="form.areaId"
                    :options="treeAreaOptions" :filterable="true" style="width: 100%;" :show-all-levels="false"
                    :props="{ 
                      emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                      checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                      value:'id',label:'label'
                    }" clearable @change="handleAreaChange">
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计量类型" prop="salesMode" >
                  <el-select v-model="form.salesMode" placeholder="请选择计量类型" style="width: 100%" @change="getDrpUnitList">
                    <el-option label="按份" value="1" />
                    <el-option label="称重" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>  
              <el-col :span="12">
                <el-form-item label="原料单位" prop="unitId">
                  <el-select v-model="form.unitId" placeholder="请选择原料单位" style="width: 100%"> 
                    <el-option v-for="item in this.unitOptions"
                        :key="item.unitId"
                        :label="item.unitName"
                        :value="item.unitId" 
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col> 
              <!-- <el-col :span="12">
                <el-form-item label="原料进价" prop="unitPrice">
                  <el-input
                    v-model="form.unitPrice"
                    placeholder="请输入原料进价"
                    @input="handleNumericInput('unitPrice', $event)"
                    @blur="formatNumericValue('unitPrice')"
                  >
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>   
              <el-col :span="12">
                <el-form-item label="条码" prop="barCode">
                  <el-input
                    v-model="form.barCode"
                    placeholder="请输入条码"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="营养信息类别" prop="nutritionTypeId"> 
                    <el-cascader
                      v-model="form.nutritionTypeId"
                      :options="cascaderOptions"
                      :props="{  
                        emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                        checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                        value:'id',label:'label'
                      }"
                      placeholder="请选择营养信息类别"
                      clearable style="width: 100%;"
                      @change="handleNutritionChange"
                    />
                </el-form-item>
              </el-col> 
              <el-col :span="12">
                <el-form-item label="营养信息" prop="nutritionId">
                  <el-select v-model="form.nutritionId" placeholder="请选择营养信息" style="width: 100%" clearable @change="chosenNutrition">
                    <el-option v-for="item in this.nutritionOptions"
                        :key="item.nutritionId"
                        :label="item.nutritionName"
                        :value="item.nutritionId" 
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col> 
              <el-col :span="24">
                <h3>营养信息</h3>
                <el-row class="nutrition-info"> 
                  <el-col :span="24">
                    <el-table :data="formTable" size="mini" >
                      <el-table-column label="加工时间（min）" prop="processingTime" align="center" width="140"></el-table-column>
                      <el-table-column label="可食部分(g/100g)" prop="edible" align="center" width="140"></el-table-column>
                      <el-table-column label="水分(g/100g)" prop="water" align="center" width="140"></el-table-column>
                      <el-table-column label="热量（千卡/100g）" prop="calories" align="center" width="140"></el-table-column>
                      <el-table-column label="蛋白质(g/100g)" prop="protein" align="center" width="140"></el-table-column>
                      <el-table-column label="脂肪(g/100g)" prop="fat" align="center" width="140"></el-table-column> 
                      <el-table-column label="碳水化合物(g/100g)" prop="carbohydrate" align="center" width="150"></el-table-column>
                      <el-table-column label="膳食纤维(g/100g)" prop="dietaryFiber" align="center" width="140"></el-table-column> 
                      <el-table-column label="胆固醇(mg/100g)" prop="cholesterol" align="center" width="140"></el-table-column> 
                    </el-table>
                  </el-col>
                  <el-col :span="24">
                    <el-table :data="formTable"  size="mini" > 
                      <el-table-column label="灰分(g/100g)" prop="ash" align="center" width="140"></el-table-column>
                      <el-table-column label="维生素A(μg/100g)" prop="vitaminA" align="center" width="140"></el-table-column>
                      <el-table-column label="胡萝卜素(μg/100g)" prop="carotene" align="center" width="140"></el-table-column>
                      <el-table-column label="视黄醇(μg/100g)" prop="retinol" align="center" width="140"></el-table-column>
                      <el-table-column label="硫胺素(mg/100g)" prop="thiamine" align="center" width="140"></el-table-column>
                      <el-table-column label="核黄素(mg/100g)" prop="riboflavin" align="center" width="140"></el-table-column>
                      <el-table-column label="烟酸/尼克酸(mg/100g)" prop="niacin" align="center" width="150"></el-table-column>
                      <el-table-column label="维生素C(mg/100g)" prop="vitaminC" align="center" width="140"></el-table-column>
                      <el-table-column label="维生素D(μg/100g)" prop="vitaminD" align="center" width="140"></el-table-column>
                    </el-table>
                  </el-col>
                  <el-col :span="24">
                    <el-table :data="formTable"  size="mini" > 
                      <el-table-column label="维生素E(mg/100g)" prop="vitaminE" align="center" width="140"></el-table-column>
                      <el-table-column label="钙(mg/100g)" prop="calcium" align="center" width="140"></el-table-column>
                      <el-table-column label="磷(mg/100g)" prop="phosphorus" align="center" width="140"></el-table-column>
                      <el-table-column label="钾(mg/100g)" prop="kalium" align="center" width="140"></el-table-column>
                      <el-table-column label="钠 (mg/100g)" prop="sodium" align="center" width="140"></el-table-column>
                      <el-table-column label="镁(mg/100g)" prop="magnesium" align="center" width="140"></el-table-column>
                      <el-table-column label="铁 (mg/100g)" prop="iron" align="center" width="150"></el-table-column>
                      <el-table-column label="锌(mg/100g)" prop="zinc" align="center" width="140"></el-table-column>
                      <el-table-column label="硒(μg/100g)" prop="selenium" align="center" width="140"></el-table-column> 
                    </el-table>
                  </el-col> 
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane> 
      </el-tabs>
    </div> 
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { systemAreaTreeApi } from "@/api/base/area";
import { systemMaterialTreeApi,getDrpUnitListApi } from "@/api/dish/material";
import { nutritionTypeListApi,nutritionAllListApi,getNutritionInfo  } from "@/api/dish/nutritionInfo";
export default {
  name: "MaterialDialog",
  props: {
    title: {
      type: String,
      default: '新增'
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      activeTab: 'basic',
      treeAreaOptions:[],//区域树
      treeTypeOptions:[],//类型树
      unitOptions:[],//单位下拉 
      nutritionTypeTreeData:[],//类别接口返回数据（未处理）
      cascaderOptions: [], // 级联选择器的选项（已处理）
      nutritionOptions:[],  
      menuMaterialNutritionDTO:{
          processingTime: '0',//加工时间（min）
          edible: '0',//可食部分(g/100g)
          water: '0',//水分(g/100g)
          calories: '0',//热量(千卡/100g)
          protein: '0',//蛋白质(g/100g) 
          fat: '0',//脂肪(g/100g)
          carbohydrate: '0',//碳水化合物(g/100g)
          dietaryFiber: '0',//膳食纤维(g/100g)
          cholesterol: '0',//胆固醇(mg/100g)
          ash: '0',//灰分(g/100g)
          vitaminA: '0',//维生素a(μg/100g) 
          carotene: '0',//胡萝卜素(μg/100g)
          retinol: '0',//视黄醇(μg/100g)
          thiamine: '0',//硫胺素(mg/100g)
          riboflavin: '0',//核黄素(mg/100g)
          niacin: '0',//烟酸/尼克酸(mg/100g)
          vitaminC: '0',//维生素c(mg/100g)
          vitaminE: '0',//维生素e(g/100g)
          calcium: '0',//钙(mg/100g)
          phosphorus: '0',//磷(mg/100g)
          kalium: '0',//钾(mg/100g) 
          sodium: '0',//钠(mg/100g)
          magnesium: '0',//镁(mg/100g)
          iron: '0',//铁(mg/100g)
          zinc: '0',//锌(mg/100g)
          selenium: '0',//硒(μg/100g)
          cuprum: '0',//铜(mg/100g) 
          manganese: '0',//锰(mg/100g)
          iodine: '0'
      },
      form: {
        materialCode: '',//原料名称
        materialName: '',//原料名称
        areaId: null,//所属区域
        materialTypeId: null,//原料类别 
        salesMode: '1',//计量类型
        unitId: '',//原料单位
        unitPrice: '',//原料进价(元)
        barCode: '',//条码
        nutritionTypeId:null,//营养信息类型
        nutritionId:null,//营养信息   
        //营养信息
        menuMaterialNutritionDTO: {}
      },
      formTable:[
        { 
          processingTime: '0',//加工时间（min）
          edible: '0',//可食部分(g/100g)
          water: '0',//水分(g/100g)
          calories: '0',//热量(千卡/100g)
          protein: '0',//蛋白质(g/100g) 
          fat: '0',//脂肪(g/100g)
          carbohydrate: '0',//碳水化合物(g/100g)
          dietaryFiber: '0',//膳食纤维(g/100g)
          cholesterol: '0',//胆固醇(mg/100g)
          ash: '0',//灰分(g/100g)
          vitaminA: '0',//维生素a(μg/100g) 
          carotene: '0',//胡萝卜素(μg/100g)
          retinol: '0',//视黄醇(μg/100g)
          thiamine: '0',//硫胺素(mg/100g)
          riboflavin: '0',//核黄素(mg/100g)
          niacin: '0',//烟酸/尼克酸(mg/100g)
          vitaminC: '0',//维生素c(mg/100g)
          vitaminE: '0',//维生素e(g/100g)
          calcium: '0',//钙(mg/100g)
          phosphorus: '0',//磷(mg/100g)
          kalium: '0',//钾(mg/100g) 
          sodium: '0',//钠(mg/100g)
          magnesium: '0',//镁(mg/100g)
          iron: '0',//铁(mg/100g)
          zinc: '0',//锌(mg/100g)
          selenium: '0',//硒(μg/100g)
          cuprum: '0',//铜(mg/100g) 
          manganese: '0',//锰(mg/100g)
          iodine: '0'
        }
      ],
      rules: {
        materialCode: [{ required: true, message: '请输入原料编码', trigger: 'blur' }],
        materialName: [{ required: true, message: '请输入原料名称', trigger: 'blur' }],
        areaId: [{ required: true, message: '请选择所属区域', trigger: 'change' }],
        materialTypeId: [{ required: true, message: '请选择原料类别', trigger: 'change' }],
        salesMode: [{ required: true, message: '请选择计量类型', trigger: 'change' }], 
        nutritionTypeId: [{ required: true, message: '请选择营养信息类别', trigger: 'change' }],
        nutritionId: [{ required: true, message: '请选择营养信息', trigger: 'change' }],
      },
      nutritionFields: [
        { label: '可食部分', prop: 'edible', unit: 'g/100g' },
        { label: '水分', prop: 'water', unit: 'g/100g' },
        { label: '热量', prop: 'calories', unit: '千卡/100g' },
        { label: '蛋白质', prop: 'protein', unit: 'g/100g' },
        { label: '脂肪', prop: 'fat', unit: 'g/100g' },
        { label: '碳水化合物', prop: 'carbohydrate', unit: 'g/100g' },
        { label: '膳食纤维', prop: 'dietaryFiber', unit: 'g/100g' },
        { label: '胆固醇', prop: 'cholesterol', unit: 'mg/100g' },
        { label: '灰分', prop: 'ash', unit: 'g/100g' },
        { label: '维生素A', prop: 'vitaminA', unit: 'μg/100g' },

        { label: '胡萝卜素', prop: 'carotene', unit: 'μg/100g' },
        { label: '视黄醇', prop: 'retinol', unit: 'μg/100g' },
        { label: '硫胺素', prop: 'thiamine', unit: 'mg/100g' },
        { label: '核黄素', prop: 'riboflavin', unit: 'mg/100g' },
        { label: '烟酸/尼克酸', prop: 'niacin', unit: 'mg/100g' },
        { label: '维生素C', prop: 'vitaminC', unit: 'mg/100g' },
        { label: '维生素E', prop: 'vitaminE', unit: 'mg/100g' },
        { label: '钙', prop: 'calcium', unit: 'mg/100g' },
        { label: '磷', prop: 'phosphorus', unit: 'mg/100g' },
        { label: '钾', prop: 'kalium', unit: 'mg/100g' },

        { label: '钠', prop: 'sodium', unit: 'mg/100g' },
        { label: '镁', prop: 'magnesium', unit: 'mg/100g' },
        { label: '铁', prop: 'iron', unit: 'mg/100g' },
        { label: '锌', prop: 'zinc', unit: 'mg/100g' },
        { label: '硒', prop: 'selenium', unit: 'μg/100g' },
        { label: '铜', prop: 'cuprum', unit: 'mg/100g' },
        { label: '锰', prop: 'manganese', unit: 'mg/100g' },
        { label: '碘', prop: 'iodine', unit: 'μg/100g' }
      ]
    };
  },
  computed: {
    // Remove dialogVisible computed property
  },
  created() {
    this.getAreaTreeData();//获取区域树
    this.getTypeTreeData();//获取原料类别树
    this.getDrpUnitList();//获取单位类型下拉 
    this.getNutritionTypeList()//获取营养信息类别树
  },
  methods: {
    //区域树
    getAreaTreeData() {
      systemAreaTreeApi({}).then((response) => {
        this.treeAreaOptions = response.data; 
      });
    },
    //基础设置-选择区域
    handleAreaChange(val){  
      // this.form.categoryId=null
      // this.getTypeTreeData()
      // this.getDrpUnitList()
    },
    //类型树
    getTypeTreeData() {
      let param = {
        areaId:this.form.areaId,
        goodsType:1
      }
      systemMaterialTreeApi(param).then((response) => {
        this.treeTypeOptions = response.data;
      });
    },
    //单位类型拉下选
    getDrpUnitList() {
      let param = { 
        "weighType":this.form.salesMode,
        "pageNum": 1, 
        "pageSize": 100
      }
      this.form.unitId=null
      getDrpUnitListApi(param).then((response) => {
        this.unitOptions = response.rows; 
      });
    }, 
    //获取营养信息类别 
    getNutritionTypeList() {
      nutritionTypeListApi().then(response => {
        this.typeTreeData = response.data;
        this.cascaderOptions = this.cascaderOptionsMethod();  
      }).catch(error => {
        console.error("Failed to fetch food types:", error);
      });
    },  
    //生成级联选择器的选项数据
    cascaderOptionsMethod() {
      if (this.typeTreeData.length==0) {
        return [];
      }
      return this.typeTreeData.map(item => ({
        id: item.id,
        label: item.name,
        parentId:0,
        level:0,
        children: item.littleTypeList.map(subItem => ({
          id: subItem.id,//父子类别value一致时选中识别不出来，加个#号区分
          label: subItem.name,
          bigType: item.name,
          parentId:item.id,
          level:1
        }))
      }));
    },
    //选中营养信息类别
    handleNutritionChange(value) {
      console.log("选中营养信息类别",value)    
      this.nutritionAllList(value)  
    }, 
    //获取营养信息下拉
    nutritionAllList(value){
      let param = {
        categoryId:value
      }
      nutritionAllListApi(param).then((response) => { 
        this.$set(this.form,"nutritionId",null)
        this.nutritionOptions = response.data;
      });
    },
    //选中营养信息
    chosenNutrition(){
      console.log("选中营养信息",this.form.nutritionId) 
      getNutritionInfo({nutritionId: this.form.nutritionId}).then((response) => {
        if(response.data){
          this.form.menuMaterialNutritionDTO = response.data
          this.formTable = [this.form.menuMaterialNutritionDTO]
        }else{
          this.form.menuMaterialNutritionDTO = this.menuMaterialNutritionDTO
          this.formTable = [this.menuMaterialNutritionDTO]
        } 
      });
    }, 
    handleNumericInput(field, event) {
      // const value = event.target.value; 
      const value = event; 
      // 只允许输入数字和小数点
      let newValue = value.replace(/[^\d.]/g, '');

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

      // 限制小数点后最多两位
      if (parts.length === 2 && parts[1].length > 2) {
        newValue = parts[0] + '.' + parts[1].substring(0, 2);
      }

      // 设置字段值
      if (field.includes('.')) {
        const [obj, prop] = field.split('.');
        this.form[obj][prop] = newValue;
      } else { 
        this.form[field] = newValue;
      }
    }, 
    formatNumericValue(field) {
      let value;
      if (field.includes('.')) {
        const [obj, prop] = field.split('.'); 
        value = this.form[obj][prop];
      } else {
        value = this.form[field];
      }

      if (!value || value === '' || value === '.') {
        value = '0.00';
      } else {
        value = parseFloat(value).toFixed(2);
      }
      console.log(value)
      if (field.includes('.')) {
        const [obj, prop] = field.split('.');
        this.form[obj][prop] = value;
      } else {
        this.form[field] = value;
      }
    },

    addProcessingMethod() {
      this.form.firstProcessList.push('');
    },

    removeProcessingMethod(index) {
      this.form.firstProcessList.splice(index, 1);
    },

    addCuttingMethod() {
      this.form.cutProcessList.push('');
    },

    removeCuttingMethod(index) {
      this.form.cutProcessList.splice(index, 1);
    },

    setFormData(row){
      console.log(row)
      // this.getTypeTreeData()
      // this.getDrpUnitList()  
      this.$set(this.form,"areaId",row.areaId)
      this.$set(this.form,"areaName",row.areaName)
      this.$set(this.form,"materialTypeId",row.materialTypeId)
      this.$set(this.form,"materialTypeName",row.materialTypeName)
      this.$set(this.form,"materialCode",row.materialCode)
      this.$set(this.form,"materialId",row.materialId)
      this.$set(this.form,"materialName",row.materialName) 
      this.$set(this.form,"salesMode",row.salesMode+'')
      this.getDrpUnitList()
      this.$set(this.form,"unitId",row.unitId)
      this.$set(this.form,"salePrice",Number((row.salePrice/100).toFixed(2))) 
      this.$set(this.form,"unitPrice",Number((row.unitPrice/100).toFixed(2))) 
      this.$set(this.form,"barCode",row.barCode)   
      if(row.nutritionTypeId){
        this.$set(this.form,"nutritionTypeId",Number(row.nutritionTypeId))   
        this.nutritionAllList(this.form.nutritionTypeId)
        setTimeout(()=>{
          this.$set(this.form,"nutritionId",row.nutritionId)
          if(this.form.nutritionId){
            getNutritionInfo({nutritionId: this.form.nutritionId}).then((response) => {
                if(response.data){
                  this.form.menuMaterialNutritionDTO = response.data
                  this.formTable = [this.form.menuMaterialNutritionDTO]
                }else{
                  this.form.menuMaterialNutritionDTO = this.menuMaterialNutritionDTO
                  this.formTable = [this.menuMaterialNutritionDTO]
                } 
            });
          }else{
              this.form.menuMaterialNutritionDTO = this.menuMaterialNutritionDTO
              this.formTable = [this.menuMaterialNutritionDTO]
          }
        },600)
      }else{
        this.$set(this.form,"nutritionType",null)
        this.form.menuMaterialNutritionDTO = this.menuMaterialNutritionDTO
        this.formTable = [this.menuMaterialNutritionDTO]
      }   
    }, 
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.salePrice = Number(this.form.salePrice);
          this.form.unitPrice = Number(this.form.unitPrice); 
          this.$emit('submit', this.form);
        }
      });
    }, 
    handleClose() {
      this.$emit('update:visible', false);
      this.$nextTick(() => {
        this.reset();
      });
    }, 
    cancel() {
      this.$emit('update:visible', false);
      this.$nextTick(() => {
        this.reset();
      });
    }, 
    reset() {
      this.form = {
        materialName: '',//原料名称
        areaId: null,//所属区域
        materialTypeId: null,//原料类别 
        salesMode: '1',//计量类型
        unitId: '',//原料单位
        unitPrice: '',//原料进价(元)
        barCode: '',//条码
        nutritionType:null,//营养信息类型
        nutritionId:null,//营养信息
        //营养信息
        menuMaterialNutritionDTO: this.menuMaterialNutritionDTO
      };
      this.formTable = [this.menuMaterialNutritionDTO]
    }
  }
};
</script>

<style lang="scss" scoped>

</style>
