<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="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>
      <!-- 定时轮灌组 -->
      <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="item.selected?'active':''" @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>
                  <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 {
      devBid:'',
      selectedGroup: 0,
      FertType: -1,
      FertPidType: -1,
      IrrCnt: 0,
      IdleTim: 0,
      FrontClearWater: 0,
      UnderClearWater: 0,
      group_list:[],
    };
  },
  
  async onLoad(options) {
    const { devBid } = options;
    this.devBid = devBid;
    await this.getConfigInfo();
  },
  methods: {
    async refresh(){
      const params = {
        devBid: this.devBid,
      };
      await this.$myRequest({
        url:'/api/v2/iot/device/fkq/refresh/',
        method:'POST',
        data: params,
        header: {
          'Content-Type': 'application/json',
          'accept': 'application/json, text/plain, */*'
        }
      })
    },
    PartTimChange(e,index){
      const value = e.detail.value;
      const item = this.group_list[index];
      const deleteKey = Object.keys(item).find(key => key.endsWith(':Status'));
      const data = {
        ...this.excludeObjectKeys(item, ['selected', 'FertTim','PartTim','Formula','group_name',deleteKey]),
      }
      // 查找data中的key以:PartTim结尾的
      const key = Object.keys(data).find(key => key.endsWith(':PartTim'));
      this.$set(this.group_list[index],key,value);
      if(item.selected){
        data[key] = value;
        this.editGroupList(data);
      }
    },
    FertTimChange(e,index){
      const value = e.detail.value;
      const item = this.group_list[index];
      const deleteKey = Object.keys(item).find(key => key.endsWith(':Status'));
      const data = {
        ...this.excludeObjectKeys(item, ['selected','FertTim','PartTim','Formula','group_name',deleteKey]),
      }
      const key = Object.keys(data).find(key => key.endsWith(':FertTim'));
      this.$set(this.group_list[index],key,value);
      if(item.selected){
        // 查找data中的key以:FertTim结尾的
        data[key] = value;
        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});
    },
    async editGroupList(data){
      const params = {
        devBid: parseInt(this.devBid),
        data,
      }
      const res = await this.$myRequest({
        url:'/api/v2/iot/device/fkq/yunshang/auto/group/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();
      }
    },
    // 实现排除对象中的某些属性的方法
    excludeObjectKeys(obj, keys) {
      return Object.keys(obj).reduce((acc, key) => {
        if (!keys.includes(key)) {
          acc[key] = obj[key];
        }
        return acc;
      }, {});
    },
    async editGroup(data){
      const params = {
        devBid: parseInt(this.devBid),
        data,
      }
      const res = await this.$myRequest({
        url:'/api/v2/iot/device/fkq/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/fkq/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
        };
      });
    },
    changeGroupStatus(index) {
      const item = this.group_list[index];
      this.$set(this.group_list[index],'selected',!item.selected);
      this.$set(this.group_list[index],'group_value',this.group_list[index].selected? 1 :0);
      const deleteKey = Object.keys(item).find(key => key.endsWith(':Status'));
      const data = {
        ...this.excludeObjectKeys(item, ['selected', 'group_value','FertTim','PartTim','Formula','group_name',deleteKey]),
        group_value: this.group_list[index].selected? 1 :0,
      }
      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();
    },
  }
};
</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;
      overflow-y: auto;
      .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>
