<template>
  <view class="auto-fertilization-container">
    <custom-card>
      <block slot="backText">自动施肥</block>
    </custom-card>
    <!-- 内容区域 -->
    <view class="content">
      <!-- 灌溉模式 -->
      <view class="setting-top-container">
        <view class="setting-item">
          <text class="setting-label">灌溉模式</text>
          <view class="radio-group">
            <view class="group-check-container" @click="selectFertType('1')">
              <view class="group-check-radius" :class="{'active': FertType == '1'}">
                <u-icon class="check-icon" name="checkmark" size="24rpx" v-if="FertType == '1'"/>
              </view>
              <text class="text" :class="FertType == '1'?'text-active':''">定时</text>
            </view>
            <view class="group-check-container" @click="selectFertType('2')" :class="{'active': FertType == '2'}" style="width: 150rpx;">
              <view class="group-check-radius" :class="{'active': FertType == '2'}">
                <u-icon class="check-icon" name="checkmark" size="24rpx" v-if="FertType == '2'"/>
              </view>
              <text class="text" :class="FertType == '2'?'text-active':''">定量</text>  
            </view>
            <view class="group-check-container" @click="selectFertType('0')" :class="{'active': FertType == '0'}">
              <view class="group-check-radius" :class="{'active': FertType == '0'}">
                <u-icon class="check-icon" name="checkmark" size="24rpx" v-if="FertType == '0'"/>
              </view>
              <text class="text" :class="FertType == '0'?'text-active':''">禁用</text>  
            </view>
          </view>
        </view>

        <!-- 配方方式 -->
        <view class="setting-item">
          <text class="setting-label">配方方式</text>
          <view class="radio-group">
            <view class="group-check-container" @click="selectFertPidType('1')" >
              <view class="group-check-radius" :class="{'active': FertPidType == '1'}">
                <u-icon class="check-icon" name="checkmark" size="24rpx" v-if="FertPidType == '1'"/>
              </view>
              <text class="text" :class="FertPidType == '1'?'text-active':''">PID</text>
            </view>
            <view class="group-check-container"  @click="selectFertPidType('2')"  :class="{'active': FertPidType == '2'}" style="width: 150rpx;">
              <view class="group-check-radius" :class="{'active': FertPidType == '2'}">
                <u-icon class="check-icon" name="checkmark" size="24rpx" v-if="FertPidType == '2'"/>
              </view>
              <text class="text" :class="FertPidType == '2'?'text-active':''">水肥比例</text>  
            </view>
            <view class="group-check-container" @click="selectFertPidType('0')"  :class="{'active': FertPidType == '0'}">
              <view class="group-check-radius" :class="{'active': FertPidType == '0'}">
                <u-icon class="check-icon" name="checkmark" size="24rpx" v-if="FertPidType == '0'"/>
              </view>
              <text class="text" :class="FertPidType == '0'?'text-active':''">禁用</text>  
            </view>
          </view>
        </view>

        <!-- 轮灌次数 -->
        <view class="setting-item">
          <text class="setting-label">轮灌次数</text>
          <view class="number-input">
            <u-number-box v-model="IrrCnt" placeholder="请输入轮灌次数" min="1" max="9999999" @minus="irrChange(IrrCnt)" @plus="irrChange(IrrCnt)"></u-number-box>
          </view>
        </view>

        <!-- 轮灌间隔 -->
        <view class="setting-item">
          <text class="setting-label">轮灌间隔</text>
          <view class="time-input">
            <input type="number" v-model="IdleTim" class="time-input-field" min="0" max="1440" placeholder="请输入轮灌间隔（分钟）" @change="idleChange(IdleTim)" />
            <text class="time-unit">分钟</text>
          </view>
        </view>

        <!-- 肥前水 -->
        <view class="setting-item">
          <text class="setting-label">肥前水</text>
          <view class="time-input">
            <input type="number" v-model="FrontClearWater" class="time-input-field"  min="0" max="1440" placeholder="请输入肥前水（秒）" @change="frontChange(FrontClearWater)" />
            <text class="time-unit">秒</text>
          </view>
        </view>

        <!-- 肥后水 -->
        <view class="setting-item">
          <text class="setting-label">肥后水</text>
          <view class="time-input">
            <input type="number" v-model="UnderClearWater" class="time-input-field"  min="0" max="1440" placeholder="请输入肥后水（秒）" @change="underChange(UnderClearWater)" />
            <text class="time-unit">秒</text>
          </view>
        </view>
      </view>
      <u-picker v-model="show" mode="selector" :range="selector" range-key="label" @confirm="confirmHandler"></u-picker>
      <!-- 定时轮灌组 -->
      <view class="round-groups-section">
        <text class="section-title">定时轮灌组</text>
        <view class="round-groups-container">
          <!-- 左侧轮灌组列表 -->
          <view class="round-groups-list">
            <view 
              v-for="(item,index) in group_list" :key="item.group"
              class="round-group-item"
              @click="selectGroup(index)"
              :class="{ active: selectedGroup === index }"
            >
              <text :class="{ 'green-text': selectedGroup === index }">{{ index + 1 }}组</text>
            </view>
          </view>

          <!-- 右侧轮灌组详情 -->
          <view class="round-group-detail">
            <view class="group-detail-item" v-for="(item,index) in group_list" :key="item.group" :id="'group-'+index">
              <view class="group-header">
                <text class="group-title">{{index + 1}}组</text>
                <view class="group-check" :class="{ active: item.selected }" @tap="()=>changeGroupStatus(index)">
                  <u-icon class="check-icon" name="checkmark" size="24rpx" />
                </view>
              </view>
              <view class="group-settings">
                <view class="setting-row">
                  <text class="setting-row-label">施肥配方</text>
                  <view @click="selectFormula(index)" class="select-group">{{ getTitle(item) }}</view>
                </view>
                <view class="setting-row">
                  <text class="setting-row-label">灌溉时长</text>
                  <input
                    type="number"
                    v-model="item.PartTim"
                    class="setting-row-input"
                    min="0"
                    max="1440"
                    placeholder="请输入灌溉时长（分钟）"
                    @change="(e) => PartTimChange(e,index)"
                  />
                  <text class="setting-row-unit">分钟</text>
                </view>
                <view class="setting-row">
                  <text class="setting-row-label">施肥时长</text>
                  <input
                    type="number"
                    v-model="item.FertTim"
                    class="setting-row-input"
                    min="0"
                    max="1440"
                    placeholder="请输入施肥时长（分钟）"
                    @change="(e) => FertTimChange(e,index)"
                  />
                  <text class="setting-row-unit">分钟</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      show: false,
      devBid:'',
      title: '选择配方',
      selector: [],
      selectedGroup: 0,
      FertType: -1,
      FertPidType: -1,
      IrrCnt: 0,
      IdleTim: 0,
      FrontClearWater: 0,
      UnderClearWater: 0,
      group_list:[],
      currentIndex: -1,
    };
  },
  
  async onLoad(options) {
    const { devBid } = options;
    this.devBid = devBid;
    await this.getInfoList();
    await this.getConfigInfo();
  },
  methods: {
    async refresh(){
      const params = {
        devBid: this.devBid,
      };
      await this.$myRequest({
        url:'/api/v2/iot/device/sf/refresh/',
        method:'POST',
        data: params,
        header: {
          'Content-Type': 'application/json',
          'accept': 'application/json, text/plain, */*'
        }
      })
    },
    getTitle(item){
      let value = '';
      if(item.labelText){
        return item.labelText;
      }
      for(let key in item){
        if(key.includes('Formula')){
          value = item[key];
          break;
        }
      }
      for(let i = 0;i< this.selector.length;i++){
        const item = this.selector[i];
        if(item.Formula == value){
          return item.label;
        }
      }
      return '选择配方';
    },
   confirmHandler(e){
    const currentItem = this.selector[e];
    const Formula = currentItem.Formula;
    const item = this.group_list[this.currentIndex];
    item.labelText = currentItem.label;
    if(item.selected){
      let keyLabel = '';
      for(let key in item){
        if(key.includes('Formula')){
          keyLabel = key
          break;
        }
      }
      const params = {
        [keyLabel]: Formula,
        group_value: 1,
      }
      this.editGroupList(params);
    }
   },
   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 list = res?.data || [];
      list.forEach((item,index)=>{
        item.label = '配方' + (index + 1);
      })
      // 8 表示未配置
      list.push({
        'Part008:Formula': 8,
        Formula: 8,
        ec: '',
        ph: '',
        wfratio: '',
        label: "未配置",
        channels: [],
      });
      console.log(list,'listlist')
      this.selector = list;
    },
    selectFertType(type){
      this.FertType = type;
      this.editGroup({
        FertType: type,
      });
    },
    selectFertPidType(type){
      this.FertPidType = type;
      this.editGroup({
        FertPidType: type,
      });
    },
    underChange(val){
      this.UnderClearWater = val;
      this.editGroup({UnderClearWater: val});
    },
    PartTimChange(e,index){
      const item = this.group_list[index];
      if(item.selected){
        item.PartTim = e.detail.value;
        const deleteKey = Object.keys(item).find(key => key.endsWith(':Status'));
        const deleteTimeR = Object.keys(item).find(key => key.endsWith(':TimR'));
        const deleteTimeT = Object.keys(item).find(key => key.endsWith(':TimT'));
        const deleteGroup = Object.keys(item).find(key => key.endsWith(':Group'));
        const getKey = Object.keys(item).find(key => key.endsWith(':PartTim'));
        const data = {
          ...this.excludeObjectKeys(item, ['selected', 'group_value','FertTim','PartTim','Formula','group_name',deleteKey,deleteTimeR,deleteTimeT,deleteGroup]),
          group_value: this.group_list[index].selected? 1 :0,
          [getKey]: item.PartTim
        }
        this.editGroupList(data);
      }
    },
    FertTimChange(e,index){
      const item = this.group_list[index];
      if(item.selected){
        item.FertTim = e.detail.value;
        const deleteKey = Object.keys(item).find(key => key.endsWith(':Status'));
        const deleteTimeR = Object.keys(item).find(key => key.endsWith(':TimR'));
        const deleteTimeT = Object.keys(item).find(key => key.endsWith(':TimT'));
        const deleteGroup = Object.keys(item).find(key => key.endsWith(':Group'));
        const getKey = Object.keys(item).find(key => key.endsWith(':Formula'));
        const data = {
          ...this.excludeObjectKeys(item, ['selected', 'group_value','FertTim','PartTim','Formula','group_name',deleteKey,deleteTimeR,deleteTimeT,deleteGroup]),
          group_value: this.group_list[index].selected? 1 :0,
          [getKey]: item.FertTim,
        }
        this.editGroupList(data);
      }
    },
    frontChange(val){
      this.FrontClearWater = val;
      this.editGroup({FrontClearWater: val});
    },
    idleChange(val){
      this.IdleTim = val;
      this.editGroup({IdleTim: val});
    },
    irrChange(val){
      this.IrrCnt = val;
      this.editGroup({IrrCnt: val});
    },
    selectFormula(index){
      this.show = true;
      this.currentIndex = index;
    },
    async editGroupList(data){
      const params = {
        devBid: parseInt(this.devBid),
        data,
      }
      const res = await this.$myRequest({
        url:'/api/v2/iot/device/sf/yunshang/auto/group/edit/',
        method:'POST',
        data: params,
        header: {
          'Content-Type': 'application/json',
          'accept': 'application/json, text/plain, */*'
        }
      })
      console.log(res,'resres')
      if(res?.code === '000000'){
        uni.showToast({
          title: '保存成功',
          icon: 'success',
        })
        this.refresh();
      }
    },
    async editGroup(data){
      const params = {
        devBid: parseInt(this.devBid),
        data,
      }
      const res = await this.$myRequest({
        url:'/api/v2/iot/device/sf/yunshang/auto/config/edit/',
        method:'POST',
        data: params,
        header: {
          'Content-Type': 'application/json',
          'accept': 'application/json, text/plain, */*'
        }
      })
      if(res?.code === '000000'){
        uni.showToast({
          title: '保存成功',
          icon: 'success',
        })
        this.refresh();
      }
    },
    async getConfigInfo(){
      const res = await this.$myRequest({
        url:'/api/v2/iot/device/sf/yunshang/auto/config/info/',
        method:'post',
        data: {
          devBid: String(this.devBid),
        },
      })
      const resData = res || {};
      this.FertPidType = resData?.FertPidType;
      this.FertType = resData?.FertType;
      this.IrrCnt = resData?.IrrCnt;
      this.IdleTim = resData?.IdleTim;
      this.FrontClearWater = resData?.FrontClearWater;
      this.UnderClearWater = resData?.UnderClearWater;
      const group_list = resData.group_list || [];
      this.group_list = group_list.map((item, index) => {
        const selected = item.group_value == 1 ? true : false;
        for (let key in item) {
          if (key.includes('PartTim')) {
            item.PartTim = item[key];
          } else if (key.includes('FertTim')) {
            item.FertTim = item[key];
          } else if (key.includes('Formula')) {
            item.Formula = item[key];
          }
        }
        return {
          ...item,
          selected
        };
      });
    },
    // 实现排除对象中的某些属性的方法
    excludeObjectKeys(obj, keys) {
      return Object.keys(obj).reduce((acc, key) => {
        if (!keys.includes(key)) {
          acc[key] = obj[key];
        }
        return acc;
      }, {});
    },
    changeGroupStatus(index) {
      const item = this.group_list[index];
      this.$set(item,'selected',!item.selected);
      const deleteKey = Object.keys(item).find(key => key.endsWith(':Status'));
      const deleteTimeR = Object.keys(item).find(key => key.endsWith(':TimR'));
      const deleteTimeT = Object.keys(item).find(key => key.endsWith(':TimT'));
      const deleteGroup = Object.keys(item).find(key => key.endsWith(':Group'));
      const data = {
        ...this.excludeObjectKeys(item, ['selected', 'group_value','FertTim','PartTim','Formula','group_name',deleteKey,deleteTimeR,deleteTimeT,deleteGroup]),
        group_value: this.group_list[index].selected? 1 :0,
      }
      console.log(data,'datadatadata')
      this.editGroupList(data);
    },
    selectGroup(index) {
      this.selectedGroup = index;
      uni.createSelectorQuery().select('#group-' + index).boundingClientRect((data) => {
        if (data) {
          uni.pageScrollTo({
            scrollTop: data.top,
            duration: 300
          });
        }
      }).exec();
    },
    // 减少轮灌次数
    decreaseRoundCount() {
      if (this.roundCount > 1) {
        this.roundCount--;
      }
    },
    // 增加轮灌次数
    increaseRoundCount() {
      this.roundCount++;
    },
    // 确认按钮点击事件
    confirm() {
      // 这里可以添加确认逻辑
      console.log('确认设置');
    }
  }
};
</script>

<style scoped lang="scss">
.auto-fertilization-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';
}
.group-check-container{
  display: flex;
  width: 120rpx;
}
.select-group{
  text-align:right;
}
.group-check-radius{
  width: 30rpx;
  height: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #ffffff;
  border: 2rpx solid #E4E7ED;
  font-size: 24rpx;
  color: #14a478;
  margin-right: 10rpx;
}
.active{
  border-color: #0BBC58;
}
.text{
  color: #666666;
  font-family: "Source Han Sans CN VF";
  font-size: 28rpx;
}
.text-active{
  color: #0BBC58;
}
/* 内容区域 */
.content {
  overflow-y: auto;
  width: calc(100% - 64rpx);
  margin-left: 32rpx;
  display:flex;
  flex-direction: column;
}
.setting-top-container{
  border: 2px solid #FFF;
  border-radius: 8px;
  padding: 32rpx;
  background: #FFF;
}
/* 设置项 */
.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #e8e8e8;

  .setting-label {
    font-size: 28rpx;
    color: #042118;
  }

  /* 单选组 */
  .radio-group {
    display: flex;
    gap: 32rpx;

    .radio-item {
      display: flex;
      align-items: center;
      gap: 8rpx;
      font-size: 26rpx;
      color: #666;
      width: 120rpx;
      &.active {
        color: #14a478;
      }

      radio {
        transform: scale(0.8);
      }
    }
  }

  /* 数字输入 */
  .number-input {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .number-btn {
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f5f5;
      border-radius: 4rpx;
      font-size: 28rpx;
      color: #666;
    }

    .number-value {
      min-width: 60rpx;
      text-align: center;
      font-size: 26rpx;
      color: #042118;
    }
  }

  /* 时间输入 */
  .time-input {
    display: flex;
    align-items: center;
    gap: 8rpx;

    .time-input-field {
      flex:1;
      height: 52rpx;
      padding: 0 16rpx;
      font-size: 26rpx;
      text-align: right;
      color: #042118;
    }

    .time-unit {
      font-size: 24rpx;
      color: #666;
    }
  }
}

/* 轮灌组区域 */
.round-groups-section {
  margin-top: 40rpx;
  flex:1;
  .section-title {
    font-size: 28rpx;
    font-weight: 500;
    color: #042118;
  }

  .round-groups-container {
    margin-top: 24rpx;
    display: flex;
    border-radius: 12rpx;
    flex:1;
    /* 左侧轮灌组列表 */
    .round-groups-list {
      width: 120rpx;
      background: #ffffff;
      border-radius: 8rpx;

      .round-group-item {
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 26rpx;
        color: #666;
        border-left-top-radius: 16rpx;
        border-left-bottom-radius: 16rpx;

        &.active {
          background: #0bbc581a;
          color:#0BBC58;
          font-weight: 700;
          color: #0bbc58;
          font-family: "Source Han Sans CN VF";
        }

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

        .green-text {
          color: #14a478;
          font-weight: 500;
        }
      }
    }

    /* 右侧轮灌组详情 */
    .round-group-detail {
      margin-left: 24rpx;
      border-radius: 16rpx;
      .group-detail-item {
        margin-bottom: 32rpx;
        padding: 24rpx;
        background: #ffffff;
        border-radius: 8rpx;
        &:last-child {
          margin-bottom: 0;
        }

        .group-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 24rpx;
          padding-bottom: 24rpx;
          border-bottom: 2rpx solid #e8e8e8;
          .group-title {
            font-size: 28rpx;
            font-weight: 500;
            color: #042118;
          }

          .group-check {
            width: 38rpx;
            height: 38rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #C9CDD4;
            color: #ffffff;
            border-radius: 50%;
            font-size: 24rpx;
            .check-icon{
              font-size: 24rpx;
            }
            &.active {
              background: #0BBC58;
              color: #fff;
            }
          }
        }

        .group-settings {
          .setting-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 24rpx;

            .setting-row-label {
              width: 120rpx;
              font-size: 26rpx;
              color: #666;
            }

            .setting-row-input {
              flex: 1;
              height: 56rpx;
              padding: 0 16rpx;
              font-size: 26rpx;
              color: #042118;
              margin-right: 12rpx;
              text-align: right;
            }

            .setting-row-unit {
              font-size: 24rpx;
              color: #666;
            }
          }
        }
      }
    }
  }
}

/* 底部确定按钮 */
.confirm-btn-container {
  padding: 32rpx;

  .confirm-btn {
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #14a478;
    border-radius: 12rpx;
    box-shadow: 0 4rpx 12rpx rgba(20, 164, 120, 0.3);

    .confirm-btn-text {
      font-size: 32rpx;
      font-weight: 500;
      color: #fff;
    }
  }
}
</style>
