<template>
  <el-dialog
    :title="title + ' - 原料'"
    :visible.sync="visible"
    width="1000px"
    append-to-body
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="handleClose"
  >
    <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="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="region">
                <el-select v-model="form.region" placeholder="请选择所属区域" style="width: 100%">
                  <el-option label="宏源大厦" value="宏源大厦" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="原料类别" prop="materialType">
                <el-select v-model="form.materialType" placeholder="请选择原料类别" style="width: 100%">
                  <el-option label="蔬菜类-宏源大厦" value="蔬菜类-宏源大厦" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计量类型" prop="measureType">
                <el-select v-model="form.measureType" placeholder="请选择计量类型" style="width: 100%">
                  <el-option label="按份" value="按份" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="原料单位" prop="unit">
                <el-select v-model="form.unit" placeholder="请选择原料单位" style="width: 100%">
                  <el-option label="条" value="条" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="原料进价" prop="purchasePrice">
                <el-input
                  v-model="form.purchasePrice"
                  placeholder="请输入原料进价"
                  @input="handleNumericInput('purchasePrice', $event)"
                  @blur="formatNumericValue('purchasePrice')"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row>

            <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="phoneticType">
                <el-select v-model="form.phoneticType" placeholder="请选择营养信息类别" style="width: 100%">
                  <el-option label="植物油/植物油" value="植物油/植物油" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="营养信息" prop="phoneticInfo">
                <el-select v-model="form.phoneticInfo" placeholder="请选择营养信息" style="width: 100%">
                  <el-option label="辣椒油" value="辣椒油" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保质期" prop="shelfLife">
                <el-input-number
                  v-model="form.shelfLife"
                  :min="0"
                  :max="999"
                  style="width: 120px"
                />
                <el-select v-model="form.shelfLifeUnit" style="width: 100px; margin-left: 10px">
                  <el-option label="按年" value="年" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="采购上限价格" prop="maxPrice">
                <el-input
                  v-model="form.maxPrice"
                  placeholder="请输入采购上限价格"
                  @input="handleNumericInput('maxPrice', $event)"
                  @blur="formatNumericValue('maxPrice')"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否需要检测" prop="needInspection">
                <el-select v-model="form.needInspection" placeholder="请选择是否需要检测" style="width: 100%">
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="供应资格证书" prop="qualificationCert">
                <el-select v-model="form.qualificationCert" placeholder="请选择供应资格证书" style="width: 100%">
                  <el-option label="请选择供应资格证书" value="" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="要求检测机构" prop="inspectionOrg">
                <el-select v-model="form.inspectionOrg" placeholder="请选择要求检测机构" style="width: 100%">
                  <el-option label="自检" value="自检" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="要求检测项目" prop="inspectionItems">
                <el-select v-model="form.inspectionItems" placeholder="请选择要求检测项目" style="width: 100%">
                  <el-option label="农残" value="农残" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="加工方法" prop="processingMethods">
                <div class="method-input-group">
                  <div v-for="(method, index) in form.processingMethods" :key="index" class="method-input-item">
                    <el-input
                      v-model="form.processingMethods[index]"
                      :placeholder="'请输入加工方法' + (index + 1)"
                    >
                      <template slot="append">
                        <el-button v-if="index === form.processingMethods.length - 1" @click="addProcessingMethod">增加</el-button>
                        <el-button v-else @click="removeProcessingMethod(index)" type="danger">删除</el-button>
                      </template>
                    </el-input>
                  </div>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="切配方法" prop="cuttingMethods">
                <div class="method-input-group">
                  <div v-for="(method, index) in form.cuttingMethods" :key="index" class="method-input-item">
                    <el-input
                      v-model="form.cuttingMethods[index]"
                      :placeholder="'请输入切配方法' + (index + 1)"
                    >
                      <template slot="append">
                        <el-button v-if="index === form.cuttingMethods.length - 1" @click="addCuttingMethod">增加</el-button>
                        <el-button v-else @click="removeCuttingMethod(index)" type="danger">删除</el-button>
                      </template>
                    </el-input>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <h3>营养信息</h3>
              <el-row :gutter="20" class="nutrition-info">
                <el-col :span="12" v-for="(item, index) in nutritionFields" :key="index">
                  <el-form-item :label="item.label" :prop="'nutrition.' + item.prop">
                    <el-input
                      v-model="form.nutrition[item.prop]"
                      :placeholder="'请输入' + item.label"
                      @input="handleNumericInput('nutrition.' + item.prop, $event)"
                      @blur="formatNumericValue('nutrition.' + item.prop)"
                    >
                      <template slot="append">{{item.unit}}</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="原料识别注册图" name="image">
        <!-- 这里添加图片上传组件 -->
      </el-tab-pane>
    </el-tabs>

    <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>
export default {
  name: "MaterialDialog",
  props: {
    title: {
      type: String,
      default: '新增'
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      activeTab: 'basic',
      form: {
        materialName: '',
        region: '',
        materialType: '',
        measureType: '',
        unit: '',
        barcode: '',
        purchasePrice: '',
        phoneticType: '',
        phoneticInfo: '',
        shelfLife: 0,
        shelfLifeUnit: '年',
        maxPrice: '',
        needInspection: '是',
        qualificationCert: '',
        inspectionOrg: '',
        inspectionItems: '',
        processingMethods: [''],
        cuttingMethods: [''],
        nutrition: {
          ediblePart: '',
          water: '',
          heat: '',
          protein: '',
          fat: '',
          carbohydrate: '',
          dietaryFiber: '',
          cholesterol: '',
          ash: '',
          vitaminA: '',
          carotene: '',
          retinol: '',
          thiamine: '',
          riboflavin: '',
          niacin: '',
          vitaminC: '',
          vitaminE: '',
          calcium: '',
          phosphorus: '',
          potassium: '',
          sodium: '',
          magnesium: '',
          iron: '',
          zinc: '',
          selenium: '',
          copper: '',
          manganese: '',
          iodine: ''
        }
      },
      rules: {
        materialName: [{ required: true, message: '请输入原料名称', trigger: 'blur' }],
        region: [{ required: true, message: '请选择所属区域', trigger: 'change' }],
        materialType: [{ required: true, message: '请选择原料类别', trigger: 'change' }]
      },
      nutritionFields: [
        { label: '可食部分', prop: 'ediblePart', unit: 'g/100g' },
        { label: '水分', prop: 'water', unit: 'g/100g' },
        { label: '热量', prop: 'heat', 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: 'potassium', 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: 'copper', unit: 'mg/100g' },
        { label: '锰', prop: 'manganese', unit: 'mg/100g' },
        { label: '碘', prop: 'iodine', unit: 'μg/100g' }
      ]
    };
  },
  computed: {
    // Remove dialogVisible computed property
  },
  methods: {
    handleNumericInput(field, event) {
      const value = event.target.value;
      // 只允许输入数字和小数点
      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);
      }

      if (field.includes('.')) {
        const [obj, prop] = field.split('.');
        this.form[obj][prop] = value;
      } else {
        this.form[field] = value;
      }
    },

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

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

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

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

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          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: '',
        region: '',
        materialType: '',
        measureType: '',
        unit: '',
        barcode: '',
        purchasePrice: '',
        phoneticType: '',
        phoneticInfo: '',
        shelfLife: 0,
        shelfLifeUnit: '年',
        maxPrice: '',
        needInspection: '是',
        qualificationCert: '',
        inspectionOrg: '',
        inspectionItems: '',
        processingMethods: [''],
        cuttingMethods: [''],
        nutrition: {
          ediblePart: '',
          water: '',
          heat: '',
          protein: '',
          fat: '',
          carbohydrate: '',
          dietaryFiber: '',
          cholesterol: '',
          ash: '',
          vitaminA: '',
          carotene: '',
          retinol: '',
          thiamine: '',
          riboflavin: '',
          niacin: '',
          vitaminC: '',
          vitaminE: '',
          calcium: '',
          phosphorus: '',
          potassium: '',
          sodium: '',
          magnesium: '',
          iron: '',
          zinc: '',
          selenium: '',
          copper: '',
          manganese: '',
          iodine: ''
        }
      };
    }
  }
};
</script>

<style lang="scss" scoped>

</style>
