<template>
  <view class="formula-setting-container">
    <custom-card>
      <block slot="backText">{{ title }}</block>
    </custom-card>

    <!-- 内容区域 -->
    <view class="content">
      <!-- 配方列表 -->
      <view class="formula-list">
        <!-- 配方1 -->
        <view class="formula-item" v-for="(recipe,index) in recipeList" :key="recipe.id">
          <view class="formula-header">
            <text class="formula-name">配方{{index + 1}}</text>
          </view>
          <view class="formula-details">
            <view class="detail-row">
              <text class="detail-label">目标EC</text>
              <view class="detail-value">
                <input
                  v-model="recipe.ec"
                  type="number"
                  placeholder="请输入EC值"
                  class="input"
                  @blur="(e)=>peifangEditHandle(index, -1, 'ec', e.detail.value)"
                />
                <text class="detail-unit">us/cm</text>
              </view>
            </view>
            <view class="detail-row">
              <text class="detail-label">目标PH</text>
              <view class="detail-value">
                <input
                  v-model="recipe.ph"
                  type="number"
                  placeholder="请输入PH值"
                  class="input"
                  @blur="(e)=>peifangEditHandle(index, -1, 'ph', e.detail.value)"
                />
              </view>
            </view>
            <view class="detail-row">
              <text class="detail-label">目标水肥比</text>
              <view class="detail-value">
                <input
                  v-model="recipe.wfratio"
                  type="number"
                  placeholder="请输入水肥比值"
                  class="input" 
                  @blur="(e)=>peifangEditHandle(index, -1, 'wfratio', e.detail.value)"
                />
              </view>
            </view>
            <view class="detail-row">
              <text class="detail-label">吸肥通道比例</text>
              <view class="detail-value">
                <input
                  v-model="channel.percentage"
                  type="number"
                  placeholder="请输入吸肥通道比例值"
                  class="input1"
                  v-for="(channel,channelIndex) in recipe.channels"
                  :key="channelIndex"
                  @blur="(e)=>peifangEditHandle(index, channelIndex, 'fertratio', e.detail.value)"
                />
                <text class="detail-unit">%</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      title: '配方设置',
      devBid: '',
      recipeList: [],
    };
  },
  onLoad(options) {
    const { devBid } = options;
    this.devBid = devBid;
    this.getInfoList();
  },
  methods: {
    async peifangEditHandle(index, channelIndex, type, value) {
      // 判断value 是否是数字
      if (isNaN(value)) {
        uni.showToast({
          title: '请输入数字',
          icon: 'none',
        })
        return;
      }
      let key = '';
      if (type == 'fertratio') {
        // 4个加一起不能超过100
        const sum = this.recipeList[index].channels.reduce(
          (acc, cur) => Number(acc) + Number(cur.percentage),
          0
        );
        if (sum > 100) {
        uni.showToast({
          title: '吸肥通道比例加起来不能超过100',
          icon: 'none',
        })
          // 如果超过了100，恢复原来的值
          this.recipeList[index].channels[channelIndex].percentage = +value;
          return;
        }
      }
      if (channelIndex == -1) {
        key = `ValveFormula:VF0${index}:${type}`;
      } else {
        key = `ValveFormula:VF0${index}:${type}${channelIndex}`;
      }
      const peifang = {
        [key]: +value
      };
      const params = {
        devBid: Number(this.devBid),
        peifang: peifang
      }
      const res = await this.$myRequest({
        url:'/api/v2/iot/device/sf/yunshang/peifang/edit/',
        method:'POST',
        data: params,
        header: {
          'Content-Type': 'application/json',
          'accept': 'application/json, text/plain, */*'
        }
      })
      const resData = res
      console.log(resData,'resDataresData')
      if (resData.code === '000000') {
        uni.showToast({
          title: '配方保存成功',
          icon: 'success',
        })
      } else {
        uni.showToast({
          title: '配方保存失败',
          icon: 'none',
        })
      }
    },
    async getInfoList(){
      this.recipeList = [];
      const params = {
        devBid: this.devBid
      }
      const res = await this.$myRequest({
        url:'/api/v2/iot/device/sf/yunshang/peifang/list/',
        method:'POST',
        data: params,
        header: {
          'Content-Type': 'application/json',
          'accept': 'application/json, text/plain, */*'
        }
      })
      const resData = res.data || [];
      for (let i = 0; i < resData.length; i++) {
        const item = resData[i];
        const recipe = {
          ec: item[`ValveFormula:VF0${i}:ec`],
          ph: item[`ValveFormula:VF0${i}:ph`],
          wfratio: item[`ValveFormula:VF0${i}:wfratio`],
          channels: []
        };
        if (
          item[`ValveFormula:VF0${i}:fertratio0`] !== null &&
          item[`ValveFormula:VF0${i}:fertratio0`] !== undefined
        ) {
          recipe.channels.push({
            percentage: item[`ValveFormula:VF0${i}:fertratio0`]
          });
        }
        if (
          item[`ValveFormula:VF0${i}:fertratio1`] !== null &&
          item[`ValveFormula:VF0${i}:fertratio1`] !== undefined
        ) {
          recipe.channels.push({
            percentage: item[`ValveFormula:VF0${i}:fertratio1`]
          });
        }
        if (
          item[`ValveFormula:VF0${i}:fertratio2`] !== null &&
          item[`ValveFormula:VF0${i}:fertratio2`] !== undefined
        ) {
          recipe.channels.push({
            percentage: item[`ValveFormula:VF0${i}:fertratio2`]
          });
        }
        if (
          item[`ValveFormula:VF0${i}:fertratio3`] !== null &&
          item[`ValveFormula:VF0${i}:fertratio3`] !== undefined
        ) {
          recipe.channels.push({
            percentage: item[`ValveFormula:VF0${i}:fertratio3`]
          });
        }
        this.recipeList.push(recipe);
      }
    },
    // 确认按钮点击事件
    confirm() {
      // 这里可以添加确认逻辑
      console.log('确认设置');
    }
  }
};
</script>

<style scoped lang="scss">
.formula-setting-container {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(180deg, #f5f6fa00 0%, #F5F6FA 23.64%, #F5F6FA 100%), linear-gradient(102deg, #BFEADD 6.77%, #B8F1E7 40.15%, #B9EEF5 84.02%);
  font-family: 'Source Han Sans CN';
  ::v-deep .u-input{
    text-align:right !important;
  }
}
.input{
  width: 100%;
  height: 80rpx;
  text-align:right;
  color:#020305;
}
.input1{
  width: 25%;
  color:#020305;
}
/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 32rpx;
  background: linear-gradient(180deg, #14a478 0%, #0f8a64 100%);
  color: #fff;

  .nav-left {
    .back-icon {
      font-size: 32rpx;
    }
  }

  .nav-center {
    .nav-title {
      font-size: 32rpx;
      font-weight: 500;
    }
  }

  .nav-right {
    display: flex;
    gap: 24rpx;

    .nav-icon {
      font-size: 28rpx;
    }
  }
}

/* 内容区域 */
.content {
  padding: 32rpx;
}

/* 配方管理 */
.formula-management {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  padding: 24rpx;
  border-radius: 12rpx;
  margin-bottom: 24rpx;

  .management-title {
    font-size: 28rpx;
    font-weight: 500;
    color: #042118;
  }

  .add-formula-btn {
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #14a478;
    color: #fff;
    border-radius: 50%;
    font-size: 28rpx;
    font-weight: bold;
  }
}

/* 配方列表 */
.formula-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

/* 配方项 */
.formula-item {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;

  .formula-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24rpx;

    .formula-name {
      font-size: 28rpx;
      font-weight: 500;
      color: #020305;
    }

    .delete-formula-btn {
      width: 32rpx;
      height: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f5f5;
      color: #666;
      border-radius: 50%;
      font-size: 24rpx;
      font-weight: bold;
    }
  }

  .formula-details {
    .detail-row {
      display: flex;
      align-items: center;
      padding: 16rpx 0;
      border-bottom: 1rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .detail-label {
        width: 150rpx;
        font-size: 26rpx;
        color: #333333;
      }

      .detail-value {
        display: flex;
        flex:1;
        align-items: center;
        justify-content: flex-end;
        height: 60rpx;
        font-size: 26rpx;
        color: #042118;
        text-align: right;
      }

      .detail-unit {
        margin-left: 8rpx;
        font-size: 24rpx;
        color: #333333;
      }
    }
  }
}

</style>
